【发布时间】:2017-02-23 11:23:02
【问题描述】:
我之前曾向question 询问过与 Redux 状态结合使用的 react 组件状态。下面的第一条代码链是我解决问题的原始建议,第二条是我得到的答案,建议我不要复制 redux 状态。这是因为复制速度很慢吗?并且在本地状态中存储尽可能少然后JS负责排序会更快吗?
在相关说明中,感觉很奇怪,第二条代码链要求我始终使用将返回对象的函数。这是唯一的出路吗?我知道在React.createClass 中,您可以存储变量来保存对象等,但是使用 es6 的扩展组件版本,您似乎必须使用函数。有没有办法解决这个问题,或者就是这样?
const Table = React.createClass({
getInitialState () {
return {contacts: []}
},
componentWillReceiveProps () {
this.setState({ contacts: this.props.data.contacts})
},
sortContacts (parameter, e){
...
},
render () {
return (
<table>
<thead>
<tr>
<th onClick={this.sortContacts.bind(this, "firstName")}>First Name</th>
</tr>
</thead>
<tbody>
{contactRows}
</tbody>
</table>
)
}
})
对比
const Table extends React.Component {
constructor(props) {
super(props);
this.state = {
sortBy: 'id' // default sort param
}
}
sortContacts(param) {
this.setState({ sortBy: param})
}
sortedContacts() {
return this.props.contacts.sort(...); // return sorted collection
}
render() {
return (
<table>
<thead>
<tr>
<th onClick={() => this.sortContacts("firstName")}>First Name</th>
</tr>
</thead>
<tbody>
{this.sortedContacts()}
</tbody>
</table>
)
}
}
【问题讨论】:
-
这个问题与 Redux 存储有关,但提供的代码是 React.js 唯一代码,根本没有实现 Redux 存储。
标签: javascript reactjs ecmascript-6 redux react-redux