使用 redux 中出现了问题,求教。

2020 年 1 月 12 日
 redfortress

function allReducer(state=Map({}), action){ let newstate = Map({}) switch (action.type) {

    case SET_CSRFTOKEN: 
        return state.set("csrftoken", action.csrftoken)

    case START_WORK: {
        console.log('开工')
        console.log(state)
        
        axios({
            method: 'post',
            headers: {'X-CSRFToken': state.get('csrftoken')},
            url: '/start/',
            data: {startdate:action.startdate,enddate:action.enddate},   
        }).then(function (response) {
            newstate = state.set("atwork", response.data.atwork)
            console.log(newstate)
          });
        console.log(newstate)
        return newstate
    }

倒数第二个 console.log(newstate)可以看到里面是有值的,最后一个 console.log(newstate)里面就是空的了,没有任何值。请问这是怎么回事?

1739 次点击
所在节点    问与答
11 条回复
ruandao
2020 年 1 月 12 日
redux 里面不要 有 异步之类的副作用
ruandao
2020 年 1 月 12 日
倒数第二个 console.log(newstate)可以看到里面是有值的,最后一个 console.log(newstate)里面就是空的了,没有任何值。请问这是怎么回事?

这个问题,是因为你不知道 promise 的运行顺序
redfortress
2020 年 1 月 12 日
@ruandao 那是不是要在 redux-saga 里执行这个就没问题了?
ruandao
2020 年 1 月 12 日
@redfortress 在哪执行都有这个问题,这个问题,是因为你不知道 promise 的运行顺序


promise 的 then 是异步执行的
ethusdt
2020 年 1 月 12 日
建议先学学基础的异步, 再用 redux
wd
2020 年 1 月 12 日
在那个 then 里面通过发一个 新的 action 来改状态.. 不过你这代码思路有问题
redfortress
2020 年 1 月 12 日
@wd 正确的思路应该是怎样的?
redfortress
2020 年 1 月 12 日
@ruandao 明白了。谢谢。
redfortress
2020 年 1 月 12 日
@FaiChou 谢谢。
wd
2020 年 1 月 13 日
redux 里面只管理状态,需要改变状态的时候通过 action 来改。action 可以通过多种方式触发,比如用户点击,或者其他状态变化引起的
wd
2020 年 1 月 13 日
https://wdicc.com/best-practice-for-react-native-redux/ 虽然写的有点早了,感觉应该还有用,希望对你有帮助。回头应该把如何 type 整理写一下。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/637322

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX