在 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组件中,我会根据传入的参数计算一个值,这个值永远不会再改变。

说:

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

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

您使用的是这些类型计算的正确方法之一。

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

但是我会把它放在 getDefaultProps() 中,因为将这种类型的数据放在那里更有意义,因为它是您 不想 改变的数据状态。

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

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

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