我打算在使用WithRouter移动到另一个路径后设置State。我原以为下面的代码1(重定向到指定的路径,2(更新状态,但它只执行1(。我的代码出了什么问题?
我打算用这种方法来改变突出显示菜单颜色的页面的当前状态。当选择菜单上的页面或触发页面中的链接功能时,就会发生这种情况。
Class App extends .. {
constructor(props) {
super(props);
this.state = {
state: null
};
}
handleState = index => e => {
this.setState({ state: index });
};
render() {
return (
<Switch>
<Route path="/SampleA">
<SampleA handleState={this.handleState}>
</Route>
<Route path="/SampleB">
<SampleB>
</Route>
</Switch>
);
}
}
Const SampleA = props => {
const handlClick = () => {
props.handleState(0);
props.history.push({
pathname: `/SampleB`
});
}
return(
<Button onClick={handleClick}>Go to B!</Button>
);
}
这可能是问题所在:
handleState = index => e => {
this.setState({ state: index });
};
应该是
handleState = index => {
this.setState({ state: index });
};
因为先前CCD_ 1是以索引作为参数并返回期望另一个参数CCD_。
现在它只获取索引并更新状态。
更新
你的功能应该是这样的:
Const SampleA = props => {
const handlClick = (e) => {
props.handleState(e, 0);
props.history.push({
pathname: `/SampleB`
});
}
return(
<Button onClick={handleClick}>Go to B!</Button>
);
}
现在,事件和索引被传递给handleState
函数,因此您可以将它们用作:
handleState = (event, index) => {
console.log(event, index);
this.setState({ state: index });
};