道具和状态中的相同数据
Same data in props and state
想象一个 Table 组件,它接收行作为其属性。
在我看来,行也代表组件的状态,因为不同的行顺序会导致不同的视图呈现。
在状态 and/or 道具中拥有完全相同的 property/data 可以吗?
短代码示例
var TableComponent = React.createClass({
// ...
getInitialState() {
return {
rows: this.props.rows
};
},
// ...
})
React.render(<TableComponent rows={[...]} />, document.body);
这是 React 组件从 props 接收数据并将其存储在状态中的一种相当常见(据我所知已被接受)的模式。唯一复杂的是处理新传入的道具(比如 ajax 添加或删除更改父组件中的行集)并管理您应用于状态副本的转换(换句话说,如果用户按列对 table 的行进行排序并重新排序行的状态副本,您可能希望将其反映在传入道具的新状态中)。
状态代表变化。
您有 table 的行数据,但在组件的生命周期中,它永远不会改变。
排序的顺序,或者哪些列应该显示或隐藏等,这是table的状态。
在您的呈现方法中,您将这种状态应用于作为 属性 传入的行数据。您的 table 组件可以将行数据视为静态值,它知道如何根据其状态以不同方式呈现。
可能是我太懒了,忽略了ReactJS的官方提示,但其中一个提到了完全相同的问题(link)。
读完这篇文章后,我得到了这个解决方案:
var TableComponent = React.createClass({
/**
* Initial component state.
*/
getInitialState() {
return {
sortBy: null,
sortDirection: null,
};
},
setSorting(column) {
// ...
this.setState({
sortBy: column,
sortDirection: sortDirection,
});
},
/**
* Sort rows based on sort state.
*/
applySorting() {
return this.props.rows.slice().sort((a, b) => {
// do sorting
});
},
render() {
var rows = this.state.sortBy ? this.applySorting() : this.props.rows;
// render table with sorted or original rows.
},
});
想象一个 Table 组件,它接收行作为其属性。
在我看来,行也代表组件的状态,因为不同的行顺序会导致不同的视图呈现。
在状态 and/or 道具中拥有完全相同的 property/data 可以吗?
短代码示例
var TableComponent = React.createClass({
// ...
getInitialState() {
return {
rows: this.props.rows
};
},
// ...
})
React.render(<TableComponent rows={[...]} />, document.body);
这是 React 组件从 props 接收数据并将其存储在状态中的一种相当常见(据我所知已被接受)的模式。唯一复杂的是处理新传入的道具(比如 ajax 添加或删除更改父组件中的行集)并管理您应用于状态副本的转换(换句话说,如果用户按列对 table 的行进行排序并重新排序行的状态副本,您可能希望将其反映在传入道具的新状态中)。
状态代表变化。
您有 table 的行数据,但在组件的生命周期中,它永远不会改变。
排序的顺序,或者哪些列应该显示或隐藏等,这是table的状态。
在您的呈现方法中,您将这种状态应用于作为 属性 传入的行数据。您的 table 组件可以将行数据视为静态值,它知道如何根据其状态以不同方式呈现。
可能是我太懒了,忽略了ReactJS的官方提示,但其中一个提到了完全相同的问题(link)。
读完这篇文章后,我得到了这个解决方案:
var TableComponent = React.createClass({
/**
* Initial component state.
*/
getInitialState() {
return {
sortBy: null,
sortDirection: null,
};
},
setSorting(column) {
// ...
this.setState({
sortBy: column,
sortDirection: sortDirection,
});
},
/**
* Sort rows based on sort state.
*/
applySorting() {
return this.props.rows.slice().sort((a, b) => {
// do sorting
});
},
render() {
var rows = this.state.sortBy ? this.applySorting() : this.props.rows;
// render table with sorted or original rows.
},
});