我对 Redux 有很好的了解。
我想知道的一件事是在大型应用程序中会有多个操作和减速器。
我的问题是
当一个动作被调度时,它如何找到合适的减速器?
减速器中可能有重复的操作吗?
即使当我查看 redux flow 时我也不明白这些问题
请解开我的困惑。
当一个动作被调度时,它如何找到合适的减速器?
当调度一个操作时,如果您使用组合减速器,则所有减速器都将被触发。适当的状态更改发生在 action.TYPE 与分派的 action.TYPE 匹配的树中。
减速器中可能存在重复的操作吗?
让我们考虑一个聊天应用程序。假设有新消息传入,并且有两个存储,分别称为 messageStore 和 unreadStore。还有一个名为 NEW_MESSAGE 的操作。所有两家商店都会在收到新消息时进行更新。
message = (state=[], action) ->
switch action.type
when NEW_MESSAGE
state # new state
unread = (state=[], action) ->
switch action.type
when NEW_MESSAGE
state # new state
combineReducer {message, unread}
Run Code Online (Sandbox Code Playgroud)
在同一个reducer中,你可以调度相同的action两次,但这是不必要的。在不同的reducer中,你可以按照上面提到的那样做。
修改后的状态数据如何从reducer传回组件?
<Provider />使得 Redux 存储可用于已包装在函数中的任何嵌套组件connect()。import { Provider } from 'react-redux';
const store = createStore(combineReducer(message, unread));
<Provider store={store}>
<App />
</Provider>
Run Code Online (Sandbox Code Playgroud)
connect()将普通的 React 组件连接到 Redux 存储。然后,函数和全局存储状态变量作为 props 传递到组件中。每次它们在全局存储中发生更改时,它们都会传递到所有连接的组件中。class ReduxEmpl extends React.Component {
render() {
return <div>I'm connected</div>
}
}
const mapStateToProps = state => ({ messages: state.message.messages })
const dispatchToProps = dispatch => ({ functionToDispatch: (params) => dispatch(functionToDispatch(params));
export default connect(mapStateToProps, mapDispatchToProps)(ReduxEmpl);
Run Code Online (Sandbox Code Playgroud)
希望我能解决你的困惑:)
| 归档时间: |
|
| 查看次数: |
973 次 |
| 最近记录: |