javascript - Onclick history.push 在子组件中反应。- 警告:在现有状态转换期间无法更新(例如在 `render` 中)
问题描述
我有一个在父组件内动态呈现的子组件。我有一个 onClick 重定向功能。每当我单击它时,我都会收到如下所示的错误消息。然后我再次点击,页面重定向到目的地
子组件
const CategoryItem = ({ img, name, categoryLink, match,history }) => (
<div className="col-3 col-sm-3 col-md-2 col-lg-2 cat-item" onClick={(event)=>{
history.push(`${match.url}/${categoryLink}`)
}}>
<img src={img} className="format-image" />
<h5 className="device-title">{name}</h5>
</div>
);
export default withRouter(CategoryItem);
父组件
const Category = () => {
return (
<section className="app-section">
<div className="app-container">
<h2>Select Category</h2>
<div className="app-row justify-content-center">
{listOfCategories.map(({ image, name, link }) => {
return (
<ChildItem key={name} img={image} name={name} categoryLink={link} />
);
})}
</div>
</div>
</section>
);
};
export default Category;
我通过使子组件成为类组件解决了无法更新错误。
我的路由器组件看起来像这样。
class Router extends Component {
render() {
let routes = (
<Switch>
<Route path={`${BASE_URL}`} exact component={HomePage} />
<Route path={`${BASE_URL}/:categorySlug`} exact component={PlanPage} />
<Route path={`${BASE_URL}/success/:sr_id`} exact component={SrCreated}/>
<Route path={`${BASE_URL}/:categorySlug/:cart_id`} exact component={CartPage} />
<Redirect to={`${BASE_URL}`} />
</Switch>
);
return (
<Layout>
{routes}
</Layout>
);
}
}
解决方案
这种错误取决于Route组件的实现渲染,错误可能在这种情况下:
<Route path="..." render={(someProps) => {
someFunction() // <-- it's not a good way to make some actions
return <SomeComponent />
}} />
可以分享一下你的路由器吗?
推荐阅读
- sql - 如果中间有其他日期,则使用单独的组分组日期范围
- javascript - 仅当输入第二个错误字符时,文本输入的边框才会改变颜色 - Javascript
- .net-core - 实体框架 - 多列上的 LeftJoin
- django - 为 Django 应用设置 gunicorn.service [Service]
- python - 如何将整数转换为数据框中的字符串?
- r - 我遇到了一些 R / Oceanographic 问题...如何比较不同长度和数字的两列
- java - 关于jUnit5动态测试并行控制的问题
- pandas - 熊猫计算基于行的百分比
- angular - OpenApi Generator 创建类型为 String 而不是 Date 的模型
- javascript - 如何捕获来自客户端渲染的所有 POST 请求调用并以编程方式请求标头?