其中是在ReactJS中放置一个值的最佳位置,该值由传入的初始参数计算一次,然后再也不会更改

Where is the best place to put a value which is computed once by the initial passed-in parameter and never changed again, in ReactJS?

本文关键字:计算 参数 一次 再也不 然后 ReactJS 一个 最佳位置      更新时间:2023-09-26

在reactjs组件中,我将根据传入的参数计算一个值,该值将永远不会更改。

说:

React.createClass({
    componentWillMount: function() {
        this.computedValue = complexComputing(this.props.feed);
    },
    render: function() {
        return <div>{this.computedValue}</div>
    }
});

你可以看到我已经把computedValue直接放进了this,但我不确定这是否是最好的地方。

经验法则是渲染应该从道具和状态派生。因为你不能改变道具,所以我会把它放在状态下。

React.createClass({
    componentWillMount: function() {
        this.setState({
            computedValue: complexComputing(this.props.feed)
        });
    },
    render: function() {
        return <div>{this.state.computedValue}</div>
    }
});

如果您只想在生命周期方法之间共享数据,那么将内容放在this上是正确的,最常见的是使内容可用于componentWillUnmount中的清理。

对于这些类型的计算,您使用的方法是正确的。

根据React组件的生命周期,有几个方法只被调用一次,也只有一次,它们是getInitialState()getDefaultProps()componentWillMount()componentDidMount()

然而,我会把它放在getDefaultProps()中,因为在那里有这种类型的数据更有意义,因为这是你不想通过状态变异的数据。