Reactjs - 为什么我不能设置状态?

Reactjs - Why can't i set state?

您好,我正在尝试从 jsonplaceholder 获取用户数据并使用该数据更新我的状态。我可以毫无问题地获取数据并将其记录到控制台。但是当我尝试设置状态时,我仍然得到一个空对象。 我感谢任何帮助。谢谢

这是我的代码:

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;

感谢大家抽出时间来回答。显然我错误地使用了 setState 并错过了它是异步的事实。

给出检查数据是否可用的条件:-

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

setState - 是一种方法。 请像这样更改代码 - this.setState({ profileDetails: data });

来自 setState

的文档

React does not guarantee that the state changes are applied immediately.

如果您想使用最新数据,请使用 回调 参数(并将其用作函数,而不是赋值,因为它是一种方法,而不是 属性)

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

设置状态的正确方法是这样,

this.setState({ profileDetails: data  })

只能通过这种方式设置状态。

改变这个

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

进入这个

this.setState({ profileDetails: data });

console.log(this.state.profileDetails); 放入 render 中,以便您查看新状态。

setState 是一个接收数据作为参数的函数。 但是你使用它就像 setState 是一个 json object