【问题标题】:Return statement in async function of redux item reducer not changing stateredux item reducer 的异步函数中的 return 语句不改变状态
【发布时间】:2020-10-20 22:48:13
【问题描述】:

我正在尝试使用 redux 来更改我的反应状态。我的其他行动案例似乎运作良好,但我坚持这一点。我认为问题的根源是异步功能,但我不确定。我根本无法使用异步函数中的 return 语句更改状态。我最好的猜测是,return 语句只能在与“if”语句相同的范围内工作,因此我不能从异步函数内部返回来更改状态。如果这就是我如何从异步函数中获取值并将其在状态中上移一级以返回它的原因?如果问题与范围无关,那么我也全神贯注。

itemReducer.js:

case ADD_ITEM:

    if (action.payload.match(/soundcloud.com/) == "soundcloud.com") {

        // First async await
        async function newItem() {

            console.log("0")
            const response = await fetch("https://soundcloud.com/oembed?format=json&url=" + action.payload );
            const json = await response.json();

            let html = json.html.match(/(?<=url=).{53}/).toString()

            let newItem = {
                id: uuidv4(),
                url: html,
                name: json.title,
                isOpen: false
            }

            console.log(newItem, ...state.items)

            return {
                items: [...state.items, newItem]
            }

        }

        newItem();
    
    }

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

    您当前的方法存在一些问题。

    第一个是你不应该使用你的 reducer 来获得更多的状态,这不是它的责任。 reducer 的职责很简单,减少,或者换句话说,导出一个新的状态。它实际上是一个状态机,它接收一个动作、一组属性并决定下一个状态应该如何。如果您在其中有异步操作,那么您就是将它与操作混合在一起。

    Action ---> Reducer ---> Store
    

    第二个问题似乎是,即使您试图使整个减速器异步,您也没有返回 newItem() 的结果。

    一个简单的解决方案

    我的建议是:

    1. newItem() 方法移出reducer 并简单地返回newItem 对象
    2. 在您的 UI 中调用 newItem() 方法,等待它,然后调用调度 ADD_ITEM 的操作并返回结果:
    const item = await newItem();
    dispatch({type: ADD_ITEM, item})
    
    1. 接收所需的操作数据并使用它来减少新状态。
    your_reducer: (state = [], action) => {
        case ADD_ITEM:
            return [...state, action.item]
    }
    

    我建议检查一些 redux examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2019-02-03
      • 2023-03-23
      • 1970-01-01
      • 2016-09-27
      相关资源
      最近更新 更多