unshift 方法不断在选择器中推送新对象

unshift method keep pushing new objects in picker

所以我在 React Native 中有一个选择器,该项目基于 api,api 包含像这样的对象数组

[{"code": "N", "description": "Normal", "id": 1, "note": null, "tolerance": 600}, {"code": "V", "description": "Variable", "id": 2, "note": null, "tolerance": null}, {"code": "F", "description": "Flexible", "id": 3, "note": null, "tolerance": null}]

我想为选择器添加某种占位符,所以我使用了 unshift 方法,但是当我单击选择器中的一个项目时,unshift 不断将新项目推入数组

render(){
let scheduleTypes = this.props.schedules;
    scheduleTypes.unshift({"description":"Schedule Type", "id": "0"});
  return(
    <PickerWrapper items={scheduleTypes} onSelect={(item) => this.setState({ type_absen: item })}/>
  )
}

我的问题是这种情况如何继续推进以及如何停止?

那是因为您 unshift-ing 在您的 render 方法中,并更改了 schedules 属性。如果您只想将该特定项目添加到您的列表中,您应该这样做:

render(){
let scheduleTypes = this.props.schedules;
  return(
    <PickerWrapper items={[{"description":"Schedule Type", "id": "0"}, ...scheduleTypes]} onSelect={(item) => this.setState({ type_absen: item })}/>
  )
}
render(){
let scheduleTypes = this.props.schedules;
scheduleTypes.unshift({"description":"Schedule Type", "id": "0"}); // <= this needs to be removed from render
  return(
    <PickerWrapper items={scheduleTypes} onSelect={(item) => this.setState({ type_absen: item })}/>
  )
}

所以,让我解释一下你的代码:

  1. 您向数组中添加了一个项目。好的!
  2. 您在 select 一个项目时重新渲染您的组件。好的!
  3. 你的组件再次调用渲染,噗,你的数组中有附加项。

我很快就会完成,这就是 React Native (RN) 组件 运行 分别是这样的:

  1. construct():这将首先构建您的组件。
  2. componentWillMount():您可以在此处放置一些代码,这些代码将在您的组件出现(渲染)之前处理。
  3. render():您要在该组件中显示的所有内容。
  4. componentDidMount(): 出现后做一些事情。

当你调用setState()时,它会重新运行你的render()函数。因为你把你的 unshift() 放在你的 render() 中,它会再 运行 unshift() 一次。这就是问题所在。

要解决此问题,您可以将 unshift() 放入 componentWillMount()construct()。有关更多详细信息,请先阅读和研究 React Native Lifecycle。 ReactJS State and Lifecycle(这个link来自ReactJS的文档,但是大同小异)