redfortress
V2EX  ›  问与答

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

  •  
  •   redfortress · Jan 12, 2020 · 2179 views
    This topic created in 2501 days ago, the information mentioned may be changed or developed.

    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)里面就是空的了,没有任何值。请问这是怎么回事?

    11 replies  •  2020-01-13 07:14:12 +08:00
    ruandao
    ruandao
    Jan 12, 2020
    1
    redux 里面不要 有 异步之类的副作用
    ruandao
    ruandao
    Jan 12, 2020
    2
    倒数第二个 console.log(newstate)可以看到里面是有值的,最后一个 console.log(newstate)里面就是空的了,没有任何值。请问这是怎么回事?

    这个问题,是因为你不知道 promise 的运行顺序
    redfortress
    redfortress
    OP
    Jan 12, 2020 via Android
    3
    @ruandao 那是不是要在 redux-saga 里执行这个就没问题了?
    ruandao
    ruandao
    Jan 12, 2020
    4
    @redfortress 在哪执行都有这个问题,这个问题,是因为你不知道 promise 的运行顺序


    promise 的 then 是异步执行的
    ethusdt
    ethusdt
    Jan 12, 2020
    5
    建议先学学基础的异步, 再用 redux
    wd
    wd
    Jan 12, 2020 via iPhone
    6
    在那个 then 里面通过发一个 新的 action 来改状态.. 不过你这代码思路有问题
    redfortress
    redfortress
    OP
    Jan 12, 2020 via Android
    7
    @wd 正确的思路应该是怎样的?
    redfortress
    redfortress
    OP
    Jan 12, 2020 via Android
    8
    @ruandao 明白了。谢谢。
    redfortress
    redfortress
    OP
    Jan 12, 2020 via Android
    9
    @FaiChou 谢谢。
    wd
    wd
    Jan 13, 2020 via iPhone
    10
    redux 里面只管理状态,需要改变状态的时候通过 action 来改。action 可以通过多种方式触发,比如用户点击,或者其他状态变化引起的
    wd
    wd
    Jan 13, 2020 via iPhone
    11
    https://wdicc.com/best-practice-for-react-native-redux/ 虽然写的有点早了,感觉应该还有用,希望对你有帮助。回头应该把如何 type 整理写一下。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4351 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 07:08 · PVG 15:08 · LAX 23:08 · JFK 02:08
    ♥ Do have faith in what you're doing.