Reactjs 将道具值传递到此.state,但是否未定义?
我需要将道具传递到我的初始状态,但当我获得最终结果的Reactjs 将道具值传递到此.state,但是否未定义?,reactjs,react-props,Reactjs,React Props,我需要将道具传递到我的初始状态,但当我获得最终结果的未定义时。 考虑下面的代码: constructor (props){ super(props); const supplier_id = parseInt(localStorage.getItem('id')); this.state ={ id: props.items_id, // get the items_id from props
未定义时。
考虑下面的代码:
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()中看到我的项目\u id
我的结果在这里
id显示未定义
这里是否有道具。id
来自某个异步调用,可能来自API?@Brianthonpson是的,它来自API。那很可能是您的问题。构造函数在组件生命周期中只调用一次。如果在呈现组件时API没有响应,那么您就错过了在构造函数中使用它的机会。您有几个选项。延迟组件的呈现,直到API响应为止。在生命周期方法中重新更新状态(可能是componentDidUpdate)。
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 (
...
)
}