本文主题:如何在react中使用redux,为了在react中更方便的使用redux,作者封装了一个专门用于react的redux库,叫做react-redux。
react-redux 将所有的组件分成两部分,分别是UI组件和容器组件。
UI组件负责UI的实现,容器组件负责管理数据和逻辑。react-redux规定,所有的UI组件都是由用户提供的,容器组件则是由 React-Redux 自动生成。
1.connect()
connect的作用是将UI组件和容器组件连接起来。connect 主要作用有两点:
1.输入逻辑:将容器组件的state映射到UI组件的props
2.输出逻辑:将用户发出的action,传送到UI组件外面去
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
function mapStateToProps(state, ownProps) {
return {
//将state.fetPubToolInfo中的数据映射到props中
...state.fetPubToolInfo
};
}
mapStateToProps()函数:当容器组件中的state发生变化时,也会引起UI组件的重新渲染。connect方法可以不传该函数,这样Ui组件就不会订阅store组件的变化,store中state的变化不会引起Ui 组件的重新渲染。
function mapDispatchToPropos(dispatch, ownProps) {
return {
getDate: (message) => {
dispatch(getDate(message));
},
};
}
mapDispatchToProps()函数:将dispatch行为映射到props中的某一个方法当中,执行props.getDate()就会执行dispatch方法来改变store中的state。
const mapDispatchToProps = {
onClick: (filter) => {
type: 'SET_VISIBILITY_FILTER',
filter: filter
};
}
2.Provider组件
Provider组件的作用是让所有组件都能拿到store中的数据。
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)