【发布时间】: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(() => { ... }, [dependants])与functional components一起使用,而不是与class base component一起使用。显示您的完整代码。 -
你能添加更多代码吗,我无法理解这里有什么问题
-
@szaman 使用类组件是项目的要求之一。我提供了上面的错误
-
@AshishKamble 你还需要什么?
标签: reactjs render react-lifecycle