React的学习(6)redux部分

thunk中间件

npm i --save redux-thunk
Redux-thunk中间件的配置和安装

import {
    
    createStore, applyMiddleware, compose} from 'redux'
import reducer from '../reducer/reducer'
import thunk from 'redux-thunk'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
    
    }):compose
const enhancer = composeEnhancers(applyMiddleware(thunk))
const store = createStore(
    reducer,
    enhancer
    // window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
export default store

这里发送请求,不是很理解为什么可以使用dispatch,后来想了下这样解释更好些:
首先dispatch是同步执行reducers生成新状态的,对于页面的操作没有问题;但是如果点击事件是请求了某个结果,需要等待结果响应后再更新视图呢?应该如何处理?所以redux引入了thunk中间件,对action进行了扩展,
看你传入的action数据类型是什么,非function,不处理,function类型的action, 自动触发函数,并且将store.dispatch传入,这里就解释了上面的disptach作为参数传入的疑惑,
对于action是function类型的
第一步返回的是函数,第二步放到仓库,它会自动运行

1.const action = getTodoList()
2.store.dispatch(action)

在这里插入图片描述

React-Redux

npm i --save react-redux

提供器:Provider
连接器:connect
在这里插入图片描述

import {
    
    connect} from 'react-redux'
class TodoList extends Component {
    
    
    constructor(props) {
    
    
        super(props);
 
    }
    render() {
    
     
        console.log(this.props)
        return ( 
            <div>
                <input 
                    value={
    
    this.props.inputValue} onChange={
    
    this.props.inputChange}/>
                <button onClick={
    
    this.props.clickButton}>提交</button>
            
            <ul>
                {
    
    
                    this.props.list.map((item,index)=>{
    
    
                        return <li key={
    
    index}>{
    
    item}</li>
                    })
                }
            </ul> 
            </div>
        );
    }
    
}
const stateToProps = (state)=>{
    
    
    return {
    
    
        inputValue: state.inputValue,
        list: state.list
    }
}
const dispathToProps = (dispatch) => {
    
    
    return {
    
    
        inputChange(e){
    
    
            let action = {
    
    
                type: 'change_input',
                value: e.target.value
            }
            dispatch(action)
        },
        clickButton(){
    
    
            let action = {
    
    
                type: 'add',
            }
            dispatch(action)
            
        }

    }
}
 //xxx映射关系
export default connect(stateToProps, dispathToProps)(TodoList);

提供器用来包裹要用到store的组件,然后进入组件进行一个连接,相当于传送命令,做一个映射,就可以把store中的state映射成props的属性,dispatchToProps是connect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store。说白了感觉都是给props添加属性,然后取出来。

学傻了,这视频这哥们不讲原理,直接上硬货,我傻了。。。。。。。。。

猜你喜欢

转载自blog.csdn.net/weixin_46013619/article/details/104940045