渲染后清除状态
Clearing state after render
考虑一下我用来获取数据的这个 HOC
function withData(Component, endpoint) {
return class extends React.Component {
state = {
result: null,
loading: false,
error: { state: false, msg: '' }
};
fetchData = async () => {
try {
this.setState({ loading: true });
const response = await axios.get(`${endpoint}/${this.props.params || ''}`);
this.setState(state => ({ result: response.data, loading: !state.loading }));
} catch (err) {
console.log('Error caugh in withData HOC', err);
this.setState({ error: true });
}
};
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps) {
if (this.props.params !== prevProps.params) {
this.fetchData();
}
}
render() {
const { result, loading } = this.state;
if (loading) return <p>Loading...</p>;
if (!result) return null;
return <Component result={result} {...this.props} />;
}
};
}
您会注意到我在说如果 !result
不渲染组件。问题是当此组件的 this.props.params
更改时,this.state.result
保留旧状态的值。我想在每次渲染后将结果重置为 null,因此它的行为与初始渲染完全相同。
我怎样才能做到这一点?
为了更清楚地说明,如果我能在 componentWillUnmount
中执行此操作,以便为下一个组件生命周期做好准备,那就太好了。但是,该组件永远不会卸载。
请注意,它必须在 HOC 中完成,而不是在它的组件中完成 returns。
在这种情况下,您会希望您的组件(由 HOC 呈现)接受一个关键选项,在我的例子中这将是 params 道具。
通常您将它们用于列表,但也可以在这里使用。当使用一个键时,如果它发生变化而不是更新,它将创建一个组件的新实例。这意味着您将不再需要 componentDidUpdate。
您可以在此处阅读有关行为的更多信息https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
考虑一下我用来获取数据的这个 HOC
function withData(Component, endpoint) {
return class extends React.Component {
state = {
result: null,
loading: false,
error: { state: false, msg: '' }
};
fetchData = async () => {
try {
this.setState({ loading: true });
const response = await axios.get(`${endpoint}/${this.props.params || ''}`);
this.setState(state => ({ result: response.data, loading: !state.loading }));
} catch (err) {
console.log('Error caugh in withData HOC', err);
this.setState({ error: true });
}
};
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps) {
if (this.props.params !== prevProps.params) {
this.fetchData();
}
}
render() {
const { result, loading } = this.state;
if (loading) return <p>Loading...</p>;
if (!result) return null;
return <Component result={result} {...this.props} />;
}
};
}
您会注意到我在说如果 !result
不渲染组件。问题是当此组件的 this.props.params
更改时,this.state.result
保留旧状态的值。我想在每次渲染后将结果重置为 null,因此它的行为与初始渲染完全相同。
我怎样才能做到这一点?
为了更清楚地说明,如果我能在 componentWillUnmount
中执行此操作,以便为下一个组件生命周期做好准备,那就太好了。但是,该组件永远不会卸载。
请注意,它必须在 HOC 中完成,而不是在它的组件中完成 returns。
在这种情况下,您会希望您的组件(由 HOC 呈现)接受一个关键选项,在我的例子中这将是 params 道具。
通常您将它们用于列表,但也可以在这里使用。当使用一个键时,如果它发生变化而不是更新,它将创建一个组件的新实例。这意味着您将不再需要 componentDidUpdate。
您可以在此处阅读有关行为的更多信息https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key