reactjs - 将 props 值传递给 this.state 但未定义?
问题描述
我需要将道具传递给我的初始状态,但是当我得到undefined
最终结果时。考虑下面的代码:
constructor (props){
super(props);
const supplier_id = parseInt(localStorage.getItem('id'));
this.state ={
id: props.items_id, // get the items_id from props
supplier_id: supplier_id,
item_name:'',
item_shortDes: '',
item_longDes: '',
price: '',
terms_agreement: '',
Location: '',
selectedFile: null,
}
this.onChange = this.onChange.bind(this);
this.updateItem = this.updateItem.bind(this);
}
updateItem(){
const itemData = this.state
const selectedFile = this.state.selectedFile
console.log(itemData)
const formData = new FormData();
formData.append('json', JSON.stringify(itemData))
formData.append('itemFile', selectedFile)
fetch(`http://localhost:9000.com/api/item/submit`, //call api here
{
method: 'post',
body: formData
})
}
但我可以在 render() 中看到我的 items_id
render() {
const { items_id } = this.props;
console.log(items_id) //i can get my items id here, but why cannot get it on this.state
return (
...
)
}
我的控制台结果在这里
id在undefined
这里显示
解决方案
推荐阅读
- c# - 如何使用 C# 在单击按钮时将同一图片的另一张图片添加到我的表单中?
- python - 减少数据框行和查找
- json - 使用 HttpClient 在 Angular 中通过外部 API 访问 Json 数据
- javascript - 无法将值更新到构造函数生成的模型中
- javascript - 在 if 条件下删除动态 html
- c++ - 在 MFC 应用程序中实现 IServiceProvider
- python-3.x - 模板匹配:为 minMaxLoc 创建掩码的有效方法?
- laravel-5 - 带有 laravel 5.6 api 和 vue.js 的博客应用
- extjs - 如何将 DLL 链接到 Extjs 应用程序
- amazon-web-services - Amazon S3 递归删除子文件夹