简体   繁体   English

Reactjs - 为什么我不能设置 state?

[英]Reactjs - Why can't i set state?

Hi i'm trying to fetch a user data from jsonplaceholder and update my state with that data.嗨,我正在尝试从 jsonplaceholder 获取用户数据并使用该数据更新我的 state。 I had no problem fetching the data and logging it to the console.我可以毫无问题地获取数据并将其记录到控制台。 But when i try to setState, i still get an empty object.但是当我尝试设置状态时,我仍然得到一个空的 object。 I appreciate any help.我很感激任何帮助。 Thanks.谢谢。

This is my code:这是我的代码:

class ProfilePage extends React.Component {
  state = {
    profileDetails: {},
  };

  componentDidMount() {
    this.fetchDetails();
  }

  fetchDetails = async () => {
    const baseUrl = "https://jsonplaceholder.typicode.com";
    const pathname = this.props.history.location.pathname;
    const response = await fetch(`${baseUrl}${pathname}`);
    const data = await response.json();
    console.log(data);                 // I can see the data i want here in the console.

    this.setState = { profileDetails: data };
    console.log(this.state.profileDetails);       // I get an empty object here.
  };

  render() {
    return <h1>Name: {this.state.profileDetails.name}</h1>;
  }
}

export default ProfilePage;

Thanks everyone for taking the time to answer.感谢大家花时间回答。 Apparently i used setState wrong and missed the fact that it's asynchronous.显然我用错了 setState 并错过了它是异步的事实。

From docs of setState来自setState的文档

React does not guarantee that the state changes are applied immediately. React 不保证立即应用 state 更改。

If you want to use up-to-date data, use callback argument (and use it as function, instead of assignment, because it is a method, not a property)如果要使用最新数据,请使用回调参数(并将其用作 function,而不是赋值,因为它是方法,而不是属性)

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

Change this改变这个

this.setState = { profileDetails: data };
console.log(this.state.profileDetails);

into this进入这个

this.setState({ profileDetails: data });

Put console.log(this.state.profileDetails);console.log(this.state.profileDetails); inside render for you to see your new state.内部渲染让您看到您的新 state。

setState is a function that recieves data as parameters. setState 是一个接收数据作为参数的 function。 but you use it like setState is a json object但是你使用它就像 setState 是 json object

setState - is a method. setState - 是一种方法。 Please change code like this - this.setState({ profileDetails: data });请像这样更改代码 - this.setState({ profileDetails: data });

The right way to set state is this,设置state的正确方法是这样的,

this.setState({ profileDetails: data  })

You have to set state by this way only.您只能通过这种方式设置 state。

Give a condition for check the data is available or not:-给出检查数据是否可用的条件:-

if(data)
this.setState = ({ profileDetails: data });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM