【问题标题】:Why my dispatch action doesn't work in use effect after request?为什么我的调度操作在请求后不起作用?
【发布时间】:2021-10-06 08:16:04
【问题描述】:

我需要帮助。我不明白为什么我的调度操作不起作用。我有 redux 商店货币列表和当前货币。

我的减速机:

export const currencyReducer = (
    state: typeState = initialState,
    action: TypeActionCurrency
): typeState => {
    switch (action.type) {
        case types.CURRENCY_FILL_LIST:
            return { ...state, list: action.payload }

        case types.CURRENCY_SET_CURRENT:
            return {
                ...state,
                current:
                    state.list.find(currency => currency._id === action.payload) ||
                    ({} as ICurrency),
            }

        default:
            return state
    }
}

我的行动:

export const setCurrencyList = (currencies: ICurrency[]) => ({
    type: types.CURRENCY_FILL_LIST,
    payload: currencies,
})

export const setCurrentCurrency = (_id: string) => ({
    type: types.CURRENCY_SET_CURRENT,
    payload: _id,
})

我的使用效果:

useEffect(() => {
        if (!list.length) {
            const fetchCurrencies = async () => {
                try {
                    const data = await $apiClient<ICurrency[]>({ url: '/currencies' })
                    dispatch(setCurrencyList(data))
                    if (!current._id) dispatch(setCurrentCurrency(data[0]._id))
                } catch (error) {
                    console.log(error)
                }
            }
            fetchCurrencies()
        }
    }, [])

我想在加载页面时提出请求并将货币列表写入 Redux 存储,如果我们没有当前货币,我们会从数据中写入默认货币。

还有一个奇怪的地方,我的redux扩展显示状态发生了变化,但是当我通过日志或者useSelector接收到的时候却是空的

enter image description here

谢谢!

【问题讨论】:

  • 你应该创建一个加载器并通过这个加载器跟踪列表何时更新

标签: reactjs redux react-redux


【解决方案1】:

我不是 100% 确定,但它应该可以工作。

 const [loader, setLoader] = useState(false);
    const list = useSelector(state => state.list)
    useEffect(() => {
            if (!list.length) {
                const fetchCurrencies = async () => {
                    try {
                        setLoader(true)
                        const data = await $apiClient<ICurrency[]>({ url: '/currencies' })
                        dispatch(setCurrencyList(data))
                        if (!current._id) dispatch(setCurrentCurrency(data[0]._id))
                    } catch (error) {
                        console.log(error)
                    } finally {
                       setLoader(false)
                    }
                }
                fetchCurrencies()
            }
        }, [])
      useEffect(() => {
            console.log(list);
        }, [loader])

【讨论】:

  • 我的失败是我在 init Provider Redux 之前放置了 useEffect。感谢您的变体
猜你喜欢
  • 2023-03-15
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2020-11-15
相关资源
最近更新 更多