无法读取默认值为null的属性“名称”

时间:2019-09-24 09:13:11

标签: reactjs

我有一个状态 我已将数据状态初始化为null 有关完整代码,请访问

https://codeshare.io/5zMyXD

在componentDidMount上调用aixos api请求

axios.post("http://localhost/axios1/index.php",data)
    .then(res=>this.setState({data:res.data}, 
()=>console.log(this.state.data)))

获取此状态

{id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"

<input defaultValue={this.state.data.name} />

如何在输入中设置这些值,例如输入fname的名称输入

4 个答案:

答案 0 :(得分:0)

{id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"

<input defaultValue={this.state.data.name} />

只使用州名 就像您提到的对象是状态一样,您可以直接从状态访问状态键 喜欢 this.state.name || this.state.mobile

答案 1 :(得分:0)

您需要显示代码以获取更好的帮助,但是 如果状态正确,则可以这样更改值:

<input type="text" name="fname" value={this.state.data.name}>

但是您的状态为空,并且显示的代码有问题,您需要正确填写状态,在您的课程中,您可以编写:

State={name:"test"}

它将正常工作。希望这可以帮助您

更新现在写成这样:

{this.state.data && this.state.data.name
    && ( < input defaultValue={this.state.data.name} /> )}

答案 2 :(得分:0)

您可以设置为通过以下方式调用axios请求

DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // No need use the same which you have initialize in onCreate
    drawerLayout.closeDrawer(GravityCompat.START)

假设您处于这种状态

drawerLayout.closeDrawer(GravityCompat.START)

然后将其呈现为

componentDidMount(){
 axios.post("http://localhost/axios1/index.php",data)
 .then(res=>this.setState({data:res.data}, 
 ()=>console.log(this.state.data)))
}

答案 3 :(得分:-1)

在您的代码中更改此内容,第31行

this.setState({res.data},()=>console.log(this.state))