首页 > 解决方案 > 组件中的 props 更改为 undefined

问题描述

我的以下组件非常不稳定。
“ this.state.list”从this.props获取值。但是状态立即变为“未定义”。
就是不知道为什么???这段代码有什么问题。

this.state.dropList

["2 mg/dL  -   Feb 21 2021 12:11:00", "5 mg/dL  -  Feb 21 2021 01:11:00"]

<ListItem dropList={this.state.dropList} />.  //call the component


export default class ListItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: []
        }
      }
    

     componentDidMount() {
        const {dropList} = this.props;
       this.setState({list: dropList})
    }


        render(){
            console.log("droplist inside:", this.state.list)
            return (
                <View>
            {
            this.state.list !== "" ?      
                <View>
                {      
                this.state.list.map((l,i) => (
                  <View key={l}>
                    <ListItem   
                    containerStyle={{padding: 4, backgroundColor:'#D3D3D3'}}
                    title={l}
                    accessible={true}
                    />
                    </View>
                ))             
              }
              </View>
              : null
           }
     </View>
            )
        }

}

日志

droplist inside: ["2 mg/dL  -   Feb 21 2021 12:11:00", "5 mg/dL  -  Feb 21 2021 01:11:00"]
droplist inside: undefined
droplist inside: undefined
droplist inside: undefined



标签: javascriptreactjsreact-native

解决方案


看来您正在将list状态的属性设置为dropList. 相反,您想按dropList. 因为dropList是原始类型的数组,所以你要做的this.setState({list: [...dropList]})不是this.setState({list: dropList}). 如果dropList是另一种类型的集合或结构,则需要按照此答案中的说明进行深度克隆。

请尝试一下,如果有帮助,请告诉我:-)


推荐阅读