状态数组值未在本机渲染中设置

State array value not getting set in render in react native

我正在尝试根据从服务器获取的数组数据呈现几个复选框。这就是我声明状态变量的方式

 this.state = {
           isLoading: true,
           checkBoxes: []
        };

//This is how I set value in componentDidMount

componentDidMount() {
    console.log("Data from JSON = " + JSON.stringify(this.props.dataSource[GLOBAL.JSONKEYS.OPTIONS]));

this.setState({
        checkBoxes: JSON.stringify(this.props.dataSource[GLOBAL.JSONKEYS.OPTIONS]),
        isLoading: false
      });
}


 render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.activityStyle}>
          <ActivityIndicator size="large" />
        </View>
      );
    }

    console.log("checkboxArray in render = " + this.state.checkBoxes);

   ... code to render view

}

下面是控制台上的结果日志

Data from JSON = [{"id":1,"value":"Category1","isChecked":false},{"id":2,"value":"Category2","isChecked":false},{"id":3,"value":"Category3","isChecked":false},{"id":4,"value":"Other","isChecked":false}]

checkboxArray in render =

如您所见,尽管我确实在 componentDidMount 中获取了数据,但 render 方法中的 checkboxArray 似乎仍然为空。看起来它的值没有设置。我在这里做错了什么吗?感谢任何帮助。

您需要从数据中获取 isChecked 值并收集它们并设置为在您的 componentDidMount 中声明它们。

    const checkBoxes = [];
    const data = this.props.dataSource[GLOBAL.JSONKEYS.OPTIONS];
    data.map((item) => {
        checkBoxes.push(item.isChecked);
    });

    this.setState({
        checkBoxes,
        isLoading: false
    });