【问题标题】:ReactJS - Re-render same component when navigate backReactJS - 导航返回时重新渲染相同的组件
【发布时间】:2018-09-27 23:34:24
【问题描述】:

我有一个类似

的 URL 结构
foo.com/details/:id

并与它一起使用 ReactRouter。如果您搜索 ID '123',该组件会呈现来自数据库的特定信息并将 URL 更新为

foo.com/details/123

如果您搜索另一个 ID '456',则 URL 会更新为

foo.com/details/456

this.props.history.push(${this.state.id});

简而言之 - 组件重新渲染。如果您重新加载或直接转到带有 URL 的 ID,则该参数将按预期工作。这是我的问题:如果您在浏览器中按下后退按钮,URL 会正确更新 (456 => 123),但组件不会重新呈现。

如何在 URL 参数更改时强制组件重新呈现?

编辑:更多代码

在构造函数中:

 if (this.props.match.params.id !== undefined) {
            this.state.id = this.props.match.params.id;
            this.getData(this.state.id)
}

在课堂上:

 <form onSubmit={this.handleSubmit}>
  <input type="text" className="form-control mx-sm-3 mb-2" placeholder="Enter ID"value=             
         {this.state.id} onChange={this.handleChange}/>
  <input type="submit" value="Search" className="btn btn-primary mb-2"/>
</form>

handleChange(event) {
      this.setState({id: event.target.value})
}

handleSubmit(event) {
      this.props.history.push(`${this.state.id}`);
      this.getData(this.state.id);
      event.preventDefault();
}

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    当道具改变时组件不会重新渲染。因此,当一个组件已经安装了 id 为 123 并且您将 id 更新为 456 时,不会触发重新渲染。您必须通过更新状态来触发更新。我建议你使用 componentDidUpdate 而不是 componentWillReceiveProps,因为它被标记为 UNSAFE,这意味着它可能会在未来的 React 版本中被弃用。您可以使用 componentDidUpdate 或 componentShouldUpdate。 以下是使用 componentDidUpdate 的实现。

    componentDidUpdate(prevProps, prevState) {
      if (this.props.match.params.id !== prevProps.match.params.id) { 
         this.setState({ id: this.props.match.params.id}); 
         this.getData(this.props.match.params.id);
        // or any other logic..
      }
    }
    

    【讨论】:

      【解决方案2】:

      url 指向same component 时,组件不会被卸载并重新安装,而是将具有不同props 的相同组件传递给它。在这里实现所需行为的方法很少。

        1234563 )。如果您找不到正确的元素来实现这一点,请转到下一个。
      1. 利用componentWillReceiveProps 并比较nextProps idcurrentProp id 并编写一个逻辑来为新ID重新初始化组件。

        componentWillReceiveProps(nextProps) {
         if (this.props.id !== nextProps.id) {
           // write your logic to update the component with new ID 
         }
        }
        

      【讨论】:

      • 我不明白你说的钥匙是什么意思,对不起。 componentWillReceiveProps 是不安全的,所以我不能使用它。
      • 如果我们需要指出解决方案,您需要显示更多代码。 key 可以用来渲染组件,但前提是组件的结构允许。
      • 用处理id状态的代码更新了上面的帖子
      • 要使用key解决方案,我们需要看到containercomponent和相关的route,如果key可以使用。否则您可以使用@shubham 的解决方案,如果您使用正确的变量来比较if (this.props.match.params.id !== prevProps.match.params.id) { this.setState({ id: this.props.match.params.id}); this.getData(this.props.match.params.id) },它应该可以工作
      • 您的第二个解决方案就像一个魅力,我确实比较了错误的值。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 2020-06-20
      • 2019-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多