问题描述
所以我有这个状态:
state = {
index: 0,
routes: [
{ key: 'first', title: 'Drop-Off', selected: true },
{ key: 'second', title: 'Pick up', selected: false },
],
};
我需要根据所选键显示和隐藏元素,如果为true
,则为false
,否则为false
。
const { routes } = this.state;
{routes[i].selected && (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}
>
...
</View>
)}
所以我需要做类似(伪代码)的事情:
this.setState({ routes: routes[old index].selected = false, routes: routes[new index].selected = true })
最好的方法是什么?
1楼
完全不变的最佳实践方法是:
this.setState(({ routes }) => ({
routes: routes.map((route, index) => ({ ...route, selected: index === toSelect })),
}));
2楼
您可以使用map()
和turnary
运算符,以便如果您的数组为空,它将显示一个备用代码。
// in your Class
routeChecker = (route) => {
if (route.selected === true) {
return (
<div>
{/* display the things */}
</div>
)
}
}
// in your return statement inside the render()
{/* maps the `routes` from state.routes array if the array has elements, /*}
{/* otherwise, shows an alternate code */}
<div>
{this.state.routes.length ?
(<div>
{this.state.routes.map(route => (this.routeChecker(route)))}
</div>)
:
(<div>
{/* alternate code if array is empty */}
</div>)
}
</div>