【发布时间】:2018-03-24 19:38:49
【问题描述】:
我的目标是使用 redux 对对象数组进行排序。
因此,我的 react-app 开始从服务器获取对象,更新 redux 存储并呈现项目列表。
然后,单击一个按钮,我的 reducer 使用相同的数组更新存储,但已排序并将新状态返回给我的容器组件,容器组件会将新道具传递给“列表组件”,从而导致重新渲染该组件。
现在我希望重新渲染的项目列表将被排序,但列表与以前相同...
为什么?有什么想法吗?
这里是代码:
App.js(容器组件)
class App extends Component {
componentWillMount() {
this.props.sortBy(GET_LIST);
}
render() {
return (
<div className="App">
<Nav sortByDate={() => {
this.props.sortBy(SORT_BY_DATE)
}} sortByLikes={() => {
this.props.sortBy(SORT_BY_LIKES)
}}/>
<Items comments={this.props.comments}/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
comments: state.comments
}
};
const mapDispatchToProps = (dispatch) => {
return {
sortBy: (action) => {
dispatch(sortBy(action));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
CommentList.js
class ListItems extends Component {
constructor(props) {
super(props);
}
getComments() {
return (this.props.comments.map(function (object) {
console.log(JSON.stringify(object));
return <Item numLikes={object.num_like} id={object.id} comment={object.comment} date={object.date}
sender={object.sender}/>
}));
}
render() {
return (
<Container>
<Row>
<Col lg={2} md={1} xs={0}/>
<Col lg={8} md={10} xs={12}>
{console.log("RENDER")}
{console.log(JSON.stringify(this.props.comments))}
{this.getComments()}
</Col>
<Col lg={2} md={16} xs={0}/>
</Row>
</Container>
);
}
}
export default ListItems;
Reducer.js
const listReducer = (state = {
comments: []
}, action) => {
function toDate(dateStr) {
const [day, month, year] = dateStr.split("/") return new Date(year, month - 1, day)
}
function commentSortedByDate(comments) {
comments.sort(function(a, b) {
return toDate(b.date) - toDate(a.date);
}) return [...comments];
}
function commentSortedByLikes(comments) {
comments.sort(function(a, b) {
return parseInt(b.num_like) - parseInt(a.num_like);
}) return [...comments];
}
switch (action.type) {
case SORT_BY_DATE:
console.log("sort by date");
state = {...state, comments: commentSortedByDate(state.comments)
}
break;
case SORT_BY_LIKES:
console.log("sort by likes");
state = {...state, comments: commentSortedByLikes(state.comments)
}
break;
case GET_LIST:
state = {...state, comments: action.payload
}
break;
}
return state;
};
export default listReducer;
【问题讨论】:
-
请贴出reducer的代码
-
请添加你的reducer的代码。上面发布的代码中的一切似乎都是正确的。
-
Reducer.js 添加!
标签: javascript arrays reactjs react-redux