React-Redux - 如何从子组件分派操作?
React-Redux - how do I dispatch actions from children components?
我正在使用 React with Redux 并遇到了这个问题。
首先,我正在创建 EditorContainer
组件,它引入了 store
并呈现:
EditorContainer.jsx:
<Provider store={store}>
<Editor></Editor>
</Provider>
在 EditorContainer.jsx 中调度操作工作得很好。
但我也想在 Editor.jsx 中发送一些操作,所以我这样做:
Editor.jsx
class Editor extends React.Component {
componentWillMount() {
store.dispatch(doSomething());
}
render() {
return (
// code
);
}
}
const mapStateToProps = state => ({
somethingPayload: somethingPayload
});
export default connect(mapStateToProps)(Editor);
当然,我在第 3 行收到 Uncaught ReferenceError: store is not defined。
不应该 connect
在这里完成工作并在 Editor 组件中包含 store
& dispatch
在我的例子中?
你应该使用 this.props.dispatch
而不是 store.dispatch
,因为 dispatch
函数是通过 props 传递的。
我正在使用 React with Redux 并遇到了这个问题。
首先,我正在创建 EditorContainer
组件,它引入了 store
并呈现:
EditorContainer.jsx:
<Provider store={store}>
<Editor></Editor>
</Provider>
在 EditorContainer.jsx 中调度操作工作得很好。
但我也想在 Editor.jsx 中发送一些操作,所以我这样做:
Editor.jsx
class Editor extends React.Component {
componentWillMount() {
store.dispatch(doSomething());
}
render() {
return (
// code
);
}
}
const mapStateToProps = state => ({
somethingPayload: somethingPayload
});
export default connect(mapStateToProps)(Editor);
当然,我在第 3 行收到 Uncaught ReferenceError: store is not defined。
不应该 connect
在这里完成工作并在 Editor 组件中包含 store
& dispatch
在我的例子中?
你应该使用 this.props.dispatch
而不是 store.dispatch
,因为 dispatch
函数是通过 props 传递的。