当前位置: 代码迷 >> JavaScript >> 如何根据索引数组更改元素的状态?
  详细解决方案

如何根据索引数组更改元素的状态?

热度:83   发布时间:2023-06-08 09:23:49.0

所以我有这个状态:

  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 })

最好的方法是什么?

完全不变的最佳实践方法是:

 this.setState(({ routes }) => ({ 
  routes: routes.map((route, index) => ({ ...route, selected: index === toSelect })),
}));

您可以使用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>
  相关解决方案