javascript - 组件中的 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
解决方案
看来您正在将list
状态的属性设置为dropList
. 相反,您想按dropList
. 因为dropList
是原始类型的数组,所以你要做的this.setState({list: [...dropList]})
不是this.setState({list: dropList})
. 如果dropList
是另一种类型的集合或结构,则需要按照此答案中的说明进行深度克隆。
请尝试一下,如果有帮助,请告诉我:-)
推荐阅读
- javascript - 如何将值从 js 发送到 CordovaActivity?
- node.js - 为什么我的 React 网站加载需要 43 秒?
- android - 从外部获取输入的自定义 Android lint 规则
- javascript - 是否有任何关于浏览器允许和不允许使用 file: 方案 URI 的综合文档?
- mongodb - MongoDB:使用匹配输入文档变量
- ansible - 在ansible中替换Jijnja模板文件中的主机变量
- sas - SAS - 将相同的数据集导出到多个 Excel 文件
- jquery - laravel:如何检查用户在 video.js 中播放了多少次视频。因为我必须限制用户只能观看 2 次视频
- r - 如何根据 r 中的 2 个日期列打开新行
- c# - 如何更新“System.IO.Packaging”的版本?