【问题标题】:setState Does Not Define State Variable (ReactJS)setState 不定义状态变量(ReactJS)
【发布时间】:2020-07-07 17:34:18
【问题描述】:

我是 ReactJS 的菜鸟,我创建了一个主页供用户在登录或注册后查看。我从我的自定义 API(NodeJS)获取数据,但是一旦我获取数据并尝试 setState,它似乎没有更新状态变量。

这是我的代码。

export class SideMenu extends Component {

constructor(props) {

        super(props)

        this.state = {
            user: {},

        };
    }


    componentDidMount() {
        this.fetchData();
        console.log(this.user);
    }

    fetchData = () => {
        axios.get("http://localhost:3001/returningusers").then((response) => {
            const data = response.data.User[0]
            console.log(data)

            this.setState({
                user: data
            })
        })
    } 

我真的需要帮助,它减慢了我的动力,我不知道如何解决它。谢谢。

【问题讨论】:

  • 如果您将componentDidMount() 中的console.log(this.user) 更改为console.log(this.state.user),它会记录数据吗?
  • 我试过了,它仍然是空的。

标签: javascript reactjs state setstate


【解决方案1】:

我不太确定这是 ES6 类方法的正确语法。试试下面的而不是箭头函数怎么样:

fetchData() {
        axios.get("http://localhost:3001/returningusers").then((response) => {
            const data = response.data.User[0]
            console.log(data)

            this.setState({
                user: data
            })
        })
    }

您还需要返回 Promises 和 awaitthen 它们。例如:

async componentDidMount() {
        await this.fetchData(); // you need to wait until this finishes
        console.log(this.state.user);
    }
    // and you need to return the Promise here
    fetchData() => {
        return axios.get("http://localhost:3001/returningusers").then((response) => {
            const data = response.data.User[0]
            console.log(data)

            this.setState({
                user: data
            })
        })
    }

【讨论】:

  • 我想我看到了问题!我已经更新了我的答案。您正在调用一个函数,然后调用一个 Promise 函数。你没有返回或等待任何东西。如果您仍有问题,请告诉我。
  • 仍然没有骰子。我也很感谢你到目前为止的帮助,非常感谢。
  • 今天早上注意到了其他事情。当您设置状态时,这些值将位于this.state。所以你的console.log 中的user var 应该是this.state.user
  • 也许你的console.log检查你的render函数。我猜这就是你可能会使用这个值的地方。
  • 仍然不工作,只返回 null/undefined。这开始变得非常令人沮丧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2016-12-20
  • 2019-07-10
  • 2019-07-31
  • 1970-01-01
  • 2019-07-19
  • 2017-02-20
相关资源
最近更新 更多