【发布时间】:2019-10-30 02:19:34
【问题描述】:
考虑一下我用来获取数据的 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 中完成,而不是在它返回的组件中。
【问题讨论】:
-
您想在每次渲染后重置
result,还是每次获取新数据时重置?在我看来,您需要做的就是将fetchData中的result设置为null,同时将loading设置为true。还是我错过了什么? -
问题在于渲染在
fetchData之前运行,这意味着当参数道具更改导致对Component进行一次额外渲染时,结果不会为空 -
无论如何你都会重新渲染,因为
loading正在更改为true -
是的,但是返回
<p>Loading...</p>;而不是<Component />我希望它具有与所有后续调用的初始时间相同的行为withData。 -
为了更清楚,如果我可以在
componentWillUnmount中执行此操作会很棒,以便为下一个组件生命周期做好准备
标签: reactjs state higher-order-components