我正在尝试解决我的代码中的问题。我有一个硬编码的状态数据,假设它来自 API 调用。在我的情况下, operationHours 的 API 数据默认没有正确排序,星期四而不是星期一。我的问题是,每当我映射数据时,我都想按星期几(星期一、星期二、星期三……)对它们进行排序。我在这里做了一个沙箱https://codesandbox.io/s/crazy-booth-4gwficlass App extends Component { state = { data: { name: "Starbucks", operationHours: { thursday: { from: "8:00", to: "20:00" }, friday: { from: "8:00", to: "20:00" }, saturday: { from: "8:00", to: "20:00" }, sunday: { from: "8:00", to: "20:00" }, monday: { from: "8:00", to: "20:00" }, tuesday: { from: "8:00", to: "20:00" }, wednesday: { from: "8:00", to: "20:00" } } } }; render() { return ( <div> <h2>{this.state.data.name}</h2> {Object.keys(this.state.data.operationHours).map(dayOfWeek => ( <div key={dayOfWeek} className="day-of-week"> {`${dayOfWeek} - ${moment( this.state.data.operationHours[dayOfWeek].from, "HH:mm" ).format("hh:mm A")} - ${moment( this.state.data.operationHours[dayOfWeek].to, "HH:mm" ).format("hh:mm A")}`} </div> ))} </div> ); }}
1 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
代替
{Object.keys(this.state.data.operationHours).map(dayOfWeek => (
<div key={dayOfWeek} className="day-of-week">
取一个带有排序日期的数组,比如
{['monday', 'tuesday', 'wednesday'].map(dayOfWeek => (
<div key={dayOfWeek} className="day-of-week">
添加回答
举报
0/150
提交
取消