【问题标题】:How to write shouldComponentUpdate with async update如何使用异步更新编写 shouldComponentUpdate
【发布时间】:2020-03-14 04:44:09
【问题描述】:

我的 React 类 EventTable 有几种模式,根据模式,它从服务器获取不同的数据并将它们显示到 <Table>。我首先让类显示静态数据,它工作得很好,包括通过来自更高组件的 prop 切换 mods。但后来我从 fetch 切换到动态数据(updateData() 中的ApiHelper 函数),现在我遇到了问题。

我无法找出正确的 shouldComponentUpdate 函数。在当前状态下,类在获取完成之前呈现,因此在初始模式下,它不显示任何内容,当模式更改时,它会显示上一次获取的数据。

例如,我尝试将旧数据与 shouldComponentUpdate 中的新数据进行比较,或者仅在 eventsLoaded 为真时更新并在获取之前将其设为假,但随后它打破了方式,组件无限更新,这有时会导致在更改模式时闪烁和在服务器流量垃圾邮件中。

class EventTable extends React.Component {
    constructor(props)
    {
        super(props);
        this.state = {
            eventsLoaded: false,
            data: undefined
        };
    }

    componentDidMount() {
        this.updateData();
    }

    componentDidUpdate() {
        this.updateData();
    }

    shouldComponentUpdate(nextProps, nextStates) {
        return this.props.mode !== nextProps.mode;
    }

    updateData() {
        if(this.props.mode === 0)
            ApiHelper.getAllEvents().then((result) => this.setState({data: result, eventsLoaded: true}));
        else if(this.props.mode === 1)
            ApiHelper.getMemberEvents(this.props.userToken).then((result) => this.setState({data: result, eventsLoaded: true}));
        else
            ApiHelper.getPastEvents().then((result) => this.setState({data: result, eventsLoaded: true}));
    }

   render() {
        //rendering a <Table> using this.state.data
   }
}

【问题讨论】:

    标签: javascript reactjs fetch-api


    【解决方案1】:

    shouldComponentUpdate 在这里对你没有任何帮助;它只是让事情变得更难(防止组件在您设置状态时重新渲染,这是您想要的)。我现在会把它拿出来,只有当你认为反应性能是一个问题,特别是这个组件是一个原因时,我才会担心实现它。

    然后,您想将前一个道具与下一个道具检查(当前在shouldComponentDidUpdate)添加到componentDidUpdate,并且仅在道具更改时调用this.updateData。如果您不将其包装在条件中,它将在每次渲染后触发,这可能导致循环行为。

    有了这些更改,初始渲染和mode 属性的更改都将触发对updateData 的调用,这将发出请求并更新状态,这将触发渲染。渲染之后,componentDidUpdate 会触发,但会看到 props 没有改变,所以它不会尝试重新获取。

    【讨论】:

    • 是的!此解决方案完美运行,非常感谢。
    猜你喜欢
    • 2013-02-09
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    相关资源
    最近更新 更多