我是redux的新手,我可以找到很多有关如何将redux状态传递给组件的信息,但并非相反,因此我不确定是否要搜索正确的词汇。但是从本质上讲,我希望能够在redux辅助函数中引用react组件的当前状态,这就是我已经完成的工作-我得到TypeError: dispatch is not a function
和handleSubmit
刚在页面上启动已加载:
App.js
render() {
return (
<div className="App">
<p>{this.state.id}</p>
<form onSubmit={this.handleSubmit(this.state.id)}>
<button type="submit">Submit</button>
</form>
</div>
)
}
const mapDispatchToProps = dispath => bindActionCreators({
handleSubmit
}, dispath);
export default connect(
mapDispatchToProps
)(App);
reducers.js
export const handleSubmit = (test) => {
window.open("http://localhost:5000/"+test);
}
//Reducer
export default (state = [], action) => {
switch (action.type) {
default:
return state;
}
};
首先,您不使用react-redux
传递props
的功能,而是尝试在组件本身上调用handleSubmit
。
[您也正在立即在onSubmit
内部调用该函数,而不是传递对函数的引用,因此将其包装在箭头函数中并使用handleSubmit
中的this.props
onSubmit={() => this.props.handleSubmit(this.state.id)}
第二,connect
的第一个参数是映射函数,按照约定获取称为mapStateTpProps
的状态的切片,将null
作为第一个参数传递。
也不需要使用bindActionCreators
,您只需传递带有函数的对象,react-redux
就会为您将它们包装在dispatch
中
export default connect(
null,
{ handleSubmit }
)(App);