【问题标题】:Render react class component on route params change在路由参数更改时渲染反应类组件
【发布时间】:2021-12-23 02:36:26
【问题描述】:

我以前只使用功能组件,所以我遇到了类组件生命周期的问题。 当参数 id 更改时,我需要重新渲染类。我可以使用 history.push(home/items/${id}) 更改参数 ID,但是随着路由的更改,页面不会重新呈现。

const getItems = () => {
      client
        .query({
          query: GET_ITEMS,
        })
        .then((result) =>
          this.setState({ items: result.data.items })
        );
    };

componentDidMount() {
    let { type } = this.props.match.params;
    this.setState({ type });

   getItems();
  }

componentDidUpdate(prevState) {
    let { type } = this.props.match.params;
    if (type !== prevState.type) {
      this.setState({ type });
    }
  }

render() {
    const { type } = this.props.match.params;

    return (
      <ul className={stl.list}>
            {this.state.items?.map(({ name }) => (
              <div>
                <li
                  style={this.state.type === name ? activeTabStyle : {}}
                  onClick={() => this.handleTabClick(name)}
                >
                  {name}
                </li>
                {this.state.type === name && <div className={stl.underline}></div>}
              </div>
            ))}
          </ul>
    );
  }



我尝试使用 componentDidUpdate,我认为它是 useEffect(() => {}, [dependants]) 的正确等价物,但它给了我一个错误,说达到了最大限制

我包含了给出错误Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. 的 componentDidUpdate 我的 componentDidUpdate 函数可能是错误的,因为我需要根据参数 id 而不是 prevState、prevProps 重新渲染。所以我尝试将参数 id 设置为 state 并使用 componentDidUpdate。

【问题讨论】:

  • 你说得对,componentDidUpdate 是正确的方法,请提供引发错误的代码和完整的错误文本。另外,afaik,你可以用函数组件做任何事情,你为什么要恢复到遗留类组件?
  • useEffect(() =&gt; { ... }, [dependants])functional components 一起使用,而不是与class base component 一起使用。显示您的完整代码。
  • 你能添加更多代码吗,我无法理解这里有什么问题
  • @szaman 使用类组件是项目的要求之一。我提供了上面的错误
  • @AshishKamble 你还需要什么?

标签: reactjs render react-lifecycle


【解决方案1】:

查看docs 以获得componentDidUpdate。您将第一个参数命名为 prevState,但第一个参数是先前的道具。您正在尝试将不存在的先前道具与当前道具进行比较,然后设置不更改先前道具的状态。这会导致无限循环。

试试这个:

componentDidUpdate(prevProps, prevState) {
  const { type } = this.props.match.params;
  if (type !== prevState.type) {
    this.setState({ type });
  }
}

考虑切换到 typescript,这些错误会立即在您的编辑器中突出显示。

请注意you probably don't need to derive state from props。您可以改为实现shouldComponentUpdate

【讨论】:

  • 它仍然没有渲染,但刷新后它正在工作。我正在使用this.handleTabClick = (input) =&gt; history.push(`/home/items/${input}`); 更改路线可以吗?
猜你喜欢
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 2017-12-23
  • 2018-07-26
  • 2021-01-31
  • 2023-04-03
  • 2016-02-24
  • 2022-10-23
相关资源
最近更新 更多