简体   繁体   English

如何在跟随链接之前创建异步 setState?

[英]How can I make an asynchronous setState before following a Link?

I want to be able to 'capture' a selection of a user clicking a link that takes them to another page.我希望能够“捕获”用户单击将他们带到另一个页面的链接的选择。 I need the users selection to display a detail page of thebselected image.我需要用户选择来显示所选图像的详细信息页面。

I'm facing the problem that the browser follows the link before react updated the state "key".我面临的问题是浏览器在反应更新 state“密钥”之前跟随链接。 The state-Change of key is not passed to the details page. key 的 state-Change 不会传递到详情页。 Is there an easy way to fix that without fetch?有没有一种简单的方法可以在不获取的情况下解决这个问题?

export default class IGallery extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      countryList: [],
      wallet: "",
      key: "",
    };
  }
  handleClick = (_key) => {
    console.log("before setState", this.state.key);
    this.setState({ key: _key }, () =>
      console.log("after setState", this.state.key)
    );
  };
  render() {
    return (
      <div className={styles.gallery}>
        <h1>Gallery</h1>
        <ImageList cols={6} rowHeight={320}>
          {this.state.countryList.map((data, idx) => (
            <ImageListItem key={idx} className={styles.imageItem}>
              <Link to="/item" onClick={() => this.handleClick(data.key)}>
                <img src={data.image} width={320} />
                <ItemDetail id={this.state.key}></ItemDetail>
              </Link>
              <ImageListItemBar
                title={"Braintube"}
                subtitle={data.key}
                actionIcon={<FavoriteBorder fontSize="large" color="pink" />}
                actionPosition="top"
              />
            </ImageListItem>
          ))}
        </ImageList>
      </div>
    );
  }
}

I expect that我希望

<ItemDetail id={this.state.key}></ItemDetail> 

passes the state value to the child component itemDetail.将 state 值传递给子组件 itemDetail。

Here is my Routing Path from index.js这是我来自 index.js 的路由路径

  <Router>
      <Header childToParent={childToParent}/>
     
      <Switch>
            <Route path="/" exact={true}>
                <Home></Home></Route>
            <Route path="/project-space">
                <ProjectSpace childToParent={wallet}></ProjectSpace> 
            </Route>
            <Route path="/about">
                <About></About></Route>
            <Route path="/item"><ItemDetail></ItemDetail></Route>
            </Switch>
           
     
      <FooterMain></FooterMain>
    </Router>

I think we need to take a step back and understand the React paradigm to answer this question.我认为我们需要退后一步,理解 React 范式来回答这个问题。

In React, state goes only one way and is not retained when a component is unmounted.在 React 中,state 只有一种方式,并且在卸载组件时不会保留。 Right now, we have the following现在,我们有以下内容

Router > SomePage > IGallery (State =....)路由器 > SomePage > IGallery(状态 =....)

and we're trying to redirect to:我们正在尝试重定向到:

Router > ItemPage路由器 > 项目页面

As you can see here, moving away to ItemPage will drop state because Router will re-render and SomePage will be unmounted.正如您在此处所见,移至 ItemPage 将丢弃 state,因为 Router 将重新呈现并且 SomePage 将被卸载。

Therefore, we have two options:因此,我们有两个选择:

  • Pass this item id in the url parameter which will then be handled by the next page在url参数中传递这个item id,然后由下一个页面处理
  • Move the state to the router parent and pass the state's setter + getter down to the page components (unrecommended)将 state 移动到路由器父级并将状态的 setter + getter 向下传递到页面组件(不推荐)

For your situation, option one is more intuitive.对于您的情况,选项一更直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM