【问题标题】:react cannot update state with easy peasy反应无法轻松更新状态
【发布时间】:2021-08-25 21:03:05
【问题描述】:

model.js

import axios from "axios"
import { action } from "easy-peasy"

export default {
    video: [],

    // Actions
    getVideo: action((state, id) => {
            axios.get(`http://localhost:8000/videos/${id}`)
            .then(res => {
                state.video = res.data[0]
            })
            .catch(err => {
                console.log(err)
            })
    })
}

Main.js

import React from 'react'
import { useEffect, useState } from 'react'
import { useStore, useStoreActions } from 'easy-peasy'

const Watch = () => {
    const video = useStore(state => state.video)
    const getVideo = useStoreActions(actions => actions.getVideo)

    useEffect(() => {
        getVideo(1)
        console.log(video)
    })

    return (
        <></>
    )

我刚开始使用 easy-peasy,所以请耐心等待...我不知道为什么状态没有更新,我看到了一些示例代码,它正在以与我相同的方式更新状态,getVideo 操作获取调用所以这不是问题,我该如何解决这个问题?

【问题讨论】:

    标签: reactjs easy-peasy


    【解决方案1】:
    useEffect(() => {
            getVideo(1)
            console.log(video)
        })
    

    这里console.log(video)getVideo(1) 完全执行后不会被调用。 console.log 显示相同的数据是很自然的。

    你可以看到它实际上改变了如下。

     useEffect(() => {
                getVideo(1)
            })
        console.log(video)
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2020-11-26
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-03-28
      相关资源
      最近更新 更多