简体   繁体   English

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

[英]How can I change the state of an element depending on the index array?

So I have this state: 所以我有这个状态:

  state = {
    index: 0,
    routes: [
      { key: 'first', title: 'Drop-Off', selected: true },
      { key: 'second', title: 'Pick up', selected: false },
    ],
  };

I need to show and hide an element depending on the selected key, if it's true show it, false hide it. 我需要根据所选键显示和隐藏元素,如果为true ,则为false ,否则为false

   const { routes } = this.state;
   {routes[i].selected && (
      <View
        style={{
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        ...
      </View>
    )}

So I need to do something like (pseudo code): 所以我需要做类似(伪代码)的事情:

this.setState({ routes: routes[old index].selected = false, routes: routes[new index].selected = true })

What could be the best approach? 最好的方法是什么?

The pure immutable best practice way would be: 完全不变的最佳实践方法是:

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

You could use the map() and a turnary operator so that if your array is empty, it will show an alternate code. 您可以使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM