私は、ユーザーが別のキーでソートできるクライアント側のソートをしたいと思います。キーは整数のみです。レンダリングされたマップされた配列のソートキーをReactで変更します
今、私は右のマップ機能の前に私のソート関数を呼び出しています:
.sort(function(a, b) {
return b.sortKey- a.sortKey;
}
ユーザーがボタンを押すと、SORTKEYは、指定した値に変更する必要があります。これはすべて関数ではなく反応コンポーネントに含まれます。コンポーネントのプロパティはコンポーネント自体によって変更されるべきではないので、ボタンのプレスでsortKeyを変更するにはどうしたらいいですか?
私の関数は、2つの並べ替えオプションとリストが含まれてレンダリング:
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(キー)関数は、理想的にはSORTKEYを変更し、新たにリストをレンダリングするが、私はレンダリングするかどうかはわかりませんでしょうユーザーがクリックした後にリストを再び表示します。
私がちょうど既知のキーでソート機能を提供すると、ソートは完全に機能します。
EDIT:API
export const fetchSurveys =() => async dispatch => {
const response = await axios.get("/api/surveys");
dispatch({ type: FETCH_SURVEYS, payload: response.data });
};
EDITからデータをフェッチ: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
私はあなたの状態を変更していないと思うので、反応がUIを更新する必要があるかどうかわかりません。 [この質問](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