首页 > 解决方案 > 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>
    );
  }
}

标签: javascriptreactjsreduxreact-router

解决方案


这种错误取决于Route组件的实现渲染,错误可能在这种情况下:

<Route path="..." render={(someProps) => {
  someFunction() // <-- it's not a good way to make some actions
  return <SomeComponent />
}} />

可以分享一下你的路由器吗?


推荐阅读