javascript - 在其他页面单击时如何更改状态?
问题描述
在项目中我有 3 页
1)当我单击第 1 页中的按钮“下一步”时,我需要重定向到第 2 页并在第 2 页中显示 toast 组件
2)当在第 2 页单击“下一步”时重定向到第 3 页
3)当点击第3页中的“返回”按钮重定向到第2页但在第2页中不显示吐司时,
如何解决这个问题,重定向工作正常我在显示 toast 时遇到问题或在第 2 页中不显示
---第1页---
class page1 extends Component {
handleSubmit = (e) => {
this.props.history.push('/page2');
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
---page2 - 我在 componentDidMount f 中写入 toast 的状态 ---
class page2 extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false,
messageToast: '',
levelToast: 'success',
}
}
componentDidMount() {
this.setState({
showToast: true,
messageToast: 'Ok',
levelToast: 'success',
}, () => {
setTimeout(() => this.setState({showToast: false}), 3000)
})
}
handleSubmit = () => {
this.props.history.push('/page3');
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
--page3---
class page3 extends Component {
handleBack = (e) => {
e.preventDefault();
this.props.history.push('/page2');
};
render() {
return (
<Fragment>
<Button
type={"close"}
title={"back"}
id={'b'}
onClick={this.handleBack}
/>
</Fragment>
);
}
}
解决方案
假设您使用的是 React Router,最简单的方法是使用进入history.push
函数的第二个参数。您可以执行以下操作:
Page1.js
class Page1 extends Component {
handleSubmit = (e) => {
this.props.history.push('/page2', {showToast: true});
// the second argument sets a state value that can be accessed in the `Page2` component
};
render() {
return (
<Fragment>
<Button
title={"Next"}
onClick={this.handleSubmit}
/>
</Fragment>
);
}
}
Page2.js
class Page2 extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false,
messageToast: '',
levelToast: 'success',
}
}
componentDidMount() {
// this is the `state` argument in the `handleSubmit` function on Page1
const shouldShowToast = this.props.location.state && this.props.location.state.showToast
this.setState({
showToast: shouldShow,
messageToast: 'Ok',
levelToast: 'success',
}, () => {
setTimeout(() => this.setState({showToast: false}), 3000)
})
}
...
...
}
'Page3.js`
class Page3 extends Component {
handleBack = (e) => {
e.preventDefault();
this.props.history.push('/page2', {showToast: false}); // set the location state.showToast to `false` this time.
};
...
...
}
希望有帮助!
推荐阅读
- java - Java 8如何处理属性为空的情况
- swift - 在 315° 圆弧上绘制圆角
- sql - 无法使用以下查询检索日期
- c# - 无法将 IQueryable 类型隐式转换为类
- python - Weird platform movement in pygame side-scrolling platformer
- c# - How to avoid so many disconnects in IoT-edge module
- python - 我使用偏移量来访问 LMDB 数据库中的元素,但它太慢了。这是为什么?
- swiftui - 如何在 SwiftUI 中使用带有 ObservedObject 的 Picker?
- python - Python script runs flawless when executed in shell, but throws unicode errors when executed as systemd service
- macos - How do I prevent an application from being used as a default opener for ANY file?