首页 > 解决方案 > 将 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这里显示

标签: reactjsreact-props

解决方案


推荐阅读