我想要客户端排序,使用户能够按不同的键进行排序。这些键只是整数。在React中更改渲染映射数组的排序键
现在,我打电话给我的排序函数映射功能前右:
.sort(function(a, b) {
return b.sortKey- a.sortKey;
}
当用户按下一个按钮,则SORTKEY应更改为指定的值。这些都包含在一个反应组件中,而不是一个函数。我读过一个组件上的属性不应该被组件本身改变,那么我将如何去改变按钮按下的sortKey?
我的渲染功能包含两个排序选项和列表:
render() {
return (
<div className="row">
<div className="col s12">
<button onClick={() => this.changeSortKey("yes")} style={{ marginRight: 5, marginTop: 5 }} className="btn">
Yes Votes
</button>
<button onClick={() => this.changeSortKey("no")} style={{ marginTop: 5 }} className="btn">
No Votes
</button>
</div>
{this.renderSurveys()}
</div>
);
}
的changeSortKey(Key)的功能会非常改变SORTKEY,然后重新呈现列表中,但我不知道如何使该列表再次在用户点击之后。
如果我只是提供一个已知键的排序功能,排序完美的作品。
编辑:从API获取数据
export const fetchSurveys =() => async dispatch => {
const response = await axios.get("/api/surveys");
dispatch({ type: FETCH_SURVEYS, payload: response.data });
};
编辑:RenderSurveys辅助函数
renderSurveys() {
//custom helper method
return this.props.surveys
.sort(function(a, b) {
return b.yes - a.yes;
})
.map(survey => {
const data = [
{ text: "Yes", value: survey.yes },
{ text: "No", value: survey.no }
];
//reverse the array and then map over it, newest first
return (
<div className="col s6">
<div key={survey._id} className="card darken-1">
<div className="card-content">
<span className="card-title">{survey.title}</span>
<p>Sent On: {new Date(survey.dateSent).toLocaleDateString()}</p>
<p>
Last responded on:{" "}
{new Date(survey.lastResponded).toLocaleDateString()}
</p>
</div>
<div className="card-action">
<a href="#">Yes: {survey.yes}</a>
<a href="#">No: {survey.no}</a>
<BarChart width={100} height={70} data={data} />
<button
onClick={() => this.props.deleteSurvey(survey._id)}
className="btn-floating btn-large red right"
>
<i className="material-icons">clear</i>
</button>
</div>
</div>
</div>
);
});
}
你能对你如何实现你的密钥更具体一点吗? – EnriqueDev
我猜你没有改变你的状态,所以反应并不知道它需要更新用户界面。看看[这个问题](https://stackoverflow.com/questions/30626030/can-you-force-a-react-component-to-rerender-without-calling-setstate),也许尝试'forceUpdate()',或对值进行排序并将结果存储在您的状态中。 –
@EnriqueDev我的sortKey还没有完全实现。我从使用redux的动作创建者处获取JSON对象中的密钥。 this.props。fetchSurveys(); – Leth