我点击了一个按钮,我将导航到另一个组件
<Link to="/result"><button onClick = {this.setDealSizeAndType} name="patient">Calculate</button></Link>
setDealSizeAndType({ target }){
const dealTypeName = target.name ;
this.setState({
dealType: dealTypeName
}, function(){
this.props.setDealType(this.state.dealType);
});
}
function mapDispatchToProps(dispatch){
return {
setDealType: (dealType) =>{
dispatch(setType(dealType));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Calculator);
但是国家没有得到确定。我没有定义。我必须在我的下一个与该组件无关的组件中获取此值。有没有办法,我可以在渲染下一个组件之前设置状态。
答案 0 :(得分:0)
调用onclick处理程序时可以使用bind函数,所以这里是更新的代码
<Link to="/result"><button onClick = {this.setDealSizeAndType.bind(this,'patient')}>Calculate</button></Link>
现在在函数setDealSizeAndType中,您将直接收到名称。
setDealSizeAndType(name){
const dealTypeName = name ;
this.setState({
dealType: dealTypeName
}, function(){
this.props.setDealType(this.state.dealType);
});
}
希望这有帮助
答案 1 :(得分:0)
您可以动态导航
,而不是使用链接<button onClick = {this.setDealSizeAndType} name="patient">Calculate</button>
setDealSizeAndType({ target }){
const dealTypeName = target.name ;
this.setState({
dealType: dealTypeName
}, function(){
this.props.setDealType(this.state.dealType);
this.props.history.push('/result'); // Programmatically navigate like this
});
}
function mapDispatchToProps(dispatch){
return {
setDealType: (dealType) =>{
dispatch(setType(dealType));
}
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Calculator));
上查看此答案