【问题标题】:React Setstate makes my state item undefined after JSONizing itReact Setstate 在 JSON 化后使我的状态项未定义
【发布时间】:2020-06-17 12:34:44
【问题描述】:

我正在尝试为自己制作锻炼日志,并作为 React 和 Node.js 的培训。我有自己的 API,其中包含许多功能,包括一个名为“/get-workouts”的 API,顾名思义,就是从数据库中获取锻炼。

这是 API

app.get('/get-workouts', (req, res) => {
db('workoutlogger').select('*')
.limit(3)
.from('workouts')
.then(workouts => {
    if(workouts.length) {
        console.log(workouts);
        res.status(200).json(workouts);
    } else {
        res.status(400).send('No workouts found');
    }
})
.catch(err => {
    console.log(err);
    res.status(404).send('Error getting workouts')
   })
})

这是我的前端:

constructor(props) {
    super(props)
    this.state = {
        workoutList: {}
    }
}

getWorkouts = () => {
    fetch('http://localhost:3001/get-workouts')
    .then(workouts => {
        workouts.json();
    })
    .then(workoutList => {
        this.setState({workoutList})
    })
    .catch(err => console.log('There was an error getting workouts', err))
}

componentDidMount() {
    this.getWorkouts();
}

如果我在获取的第一个 .then() 中 console.log “锻炼”。我的 API 清楚地记录了我登录的最后 3 次锻炼的列表,最初,this.state.workoutList 是一个对象。但是一旦 set.state 应该将锻炼列表设置为我的锻炼列表,它就会记录为未定义,我无法显示它。问题出在哪里?

【问题讨论】:

  • 您应该返回一些东西,以便下一个then()'s 可以使用它们。在你的情况下,返回workouts.json()

标签: javascript reactjs fetch state


【解决方案1】:

您需要在连续的.thens 之间传递值,它们不会被隐式传递。一个.then 的返回值成为下一个的参数。这样做:

.then(workouts => workouts.json())
.then(workoutList => {
    this.setState({workoutList})
})

删除花括号意味着它隐式返回workouts.json(),然后它将成为下一个.then中的workoutList参数

【讨论】:

  • 非常感谢!所以基本上这要么是你的解决方案,要么我应该在我的“workouts.json()”之前添加“return”?
【解决方案2】:

这里需要正确理解箭头函数。

不带花括号的箭头函数隐式返回下一条语句的计算结果。但是,如果您使用花括号,您将形成一个块,它只是一个语句列表(其计算结果为undefined)。因此在这种情况下我们需要显式使用return

constructor(props) {
    super(props)
    this.state = {
        workoutList: {}
    }
}

getWorkouts = () => {
    fetch('http://localhost:3001/get-workouts')
    .then(workouts => {
        return workouts.json();
    })
    // above then fn can also be written (without curly braces) as below:
    // .then(workouts => workouts.json()) -- removing curly braces returns result of statement implicitly
    .then(workoutList => {
        this.setState({workoutList})
    })
    .catch(err => console.log('There was an error getting workouts', err))
}

componentDidMount() {
    this.getWorkouts();
}

【讨论】:

    猜你喜欢
    • 2018-04-07
    • 2018-08-22
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2019-07-12
    • 2020-01-15
    相关资源
    最近更新 更多