react-redux注意点

2019-11-06  本文已影响0人  参商_70a0
import {Provider} from 'react-redux'
import store from "./store/index"
const App=(
    <Provider store={store}>
        <TodoList />
    </Provider>
);

ReactDOM.render(App, document.getElementById('root'));

Provider是react-redux的一个核心API,连接store,使加上Connect变成容器组件的内部组件,有能力获取store里的数据。

import React from 'react'
import {connect} from 'react-redux'
// class TodoList extends Component {
    
//     render() {
        
//     }
// }
//如果只有一个render方法可以将其改成无状态组件,可以提升性能
const TodoList=(props)=>{
    const {inputValue,handleClick,inputChangeValue,list} =props
    return (
        <div>
            <input type="text" value={inputValue} onChange={inputChangeValue}/>
            <button onClick={handleClick}>提交</button>
            <ul>
                {
                    list.map((item,index)=>{
                        return <li key={index}>{item}</li>
                    })
                }
            </ul>
        </div>
    )
}



//会将store中的inputValue映射到props的inputValue
//mapStateToProps还有第二个参数,代表该容器组件的props
const mapStateToProps=(state , ownProps)=>{
    console.log(ownProps)
    return {
        inputValue:state.inputValue,
        list:state.list
    }
}
//将store.dispatch方法挂载到props上
const mapDispatchToProps=(dispatch,ownProps)=>{
  console.log(ownProps)
    return {
        inputChangeValue(e){
            const action={
                type:'change_input_value',
                value:e.target.value
            }
            dispatch(action);
        },
        handleClick: ()=>{
            const action={
                type:'add_item'
            }
            dispatch(action);
        }
    }
}

//它生成了一个容器组件,TodoList是UI组件,加上connect之后export了一个容器组件
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);




combineReducers 可以将多个零散的reducer合并为一个大的reducer

import {combineReducers} from 'redux';
import headerReducer from '../common/header/store/reducer';
export default combineReducers({
    header:headerReducer
})
上一篇 下一篇

猜你喜欢

热点阅读