【问题标题】:Clearing state after render渲染后清除状态
【发布时间】: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
  • 是的,但是返回 &lt;p&gt;Loading...&lt;/p&gt;; 而不是 &lt;Component /&gt; 我希望它具有与所有后续调用的初始时间相同的行为 withData
  • 为了更清楚,如果我可以在componentWillUnmount 中执行此操作会很棒,以便为下一个组件生命周期做好准备

标签: reactjs state higher-order-components


【解决方案1】:

在这种情况下,您会希望您的组件(由 HOC 呈现)接受一个关键选项,在我的情况下,这将是 params 道具。

通常您将它们用于列表,但也可以在此处使用。当一个键被使用时,如果它改变而不是更新,它将创建一个新的组件实例。这意味着您将不再需要 componentDidUpdate。

你可以在这里https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key阅读更多关于行为的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2017-01-01
    相关资源
    最近更新 更多