setState不会更改初始状态

时间:2019-12-13 15:33:25

标签: react-native

我正在做react-native-modal,用户单击并查看不同的汽车模型,然后选择一个。在onPress的{​​{1}}中,我将id传递给a函数,然后使用Touchableopacity

id从touchbleopacity传递给函数,并且被打印出来,但是当我使用setSelectedCarModelID时,它不会更新状态。

setSelectedCarModelID

1 个答案:

答案 0 :(得分:0)

这怎么样?通常,我使用构造函数来初始化状态

// this is where I initiated the state
constructor(props) {
  super(props);
  this.state = {
    selectedCarModelID: null, 
    setSelectedCarModelID: null
  };
}
// the function that is supposed to handle state update
const changeSelectedCarModelId = (id) => {
  console.log(id, ":: id")
  // setSelectedCarModelID(id)
  this.setState({ setSelectedCarModelID: id})
}
// 
<TouchableOpacity
  onPress={() => {
    changeSelectedCarModelId(carModel.id);
  }}
  key={carModel.id.toString()}
  style={{ width: 50, height: 80 }}
>