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

时间:2019-02-12 18:36:06

标签: javascript reactjs ecmascript-6

所以我有这种状态:

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

如果要true显示它,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 })

什么是最好的方法?

2 个答案:

答案 0 :(得分:2)

纯一​​成不变的最佳实践方法是:

Application.WorksheetFunction.Sum(sourceRange) + Application.WorksheetFunction.Sum(destRange)

答案 1 :(得分:0)

您可以使用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>