【问题标题】:Get Data using Redux with react hooks使用 Redux 和 react hooks 获取数据
【发布时间】:2020-06-08 02:32:19
【问题描述】:

所以我刚开始学习钩子,并尝试将 Redux 与它们一起使用。我一直在尝试 redux new api,但现在我似乎无法获得我想要的数据。当我执行 console.log() 时,我看到承诺得到解决,并且在 [[PromiseValue]] 中我看到了数据,但是如何将其从那里取出到我的组件中。

const Main = ({props}) => {
 const [cloth,setCloth]=useState([])
 const items = useSelector((state) => state);
 const dispatch = useDispatch()
 let getItems = getAllItems(
    () => dispatch({ type: 'GET_ITEMS' }),
    [dispatch]
  )
 console.log(getItems)

这是我的console.log()的图片

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    首先要使用带有异步操作的redux,您需要使用redux-thunk中间件:

    npm i redux-thunk
    

    然后像这样使用它:

    import { createStore, applyMiddleware } from 'redux';
    const store = createStore(rootReducer, applyMiddleware(thunk));
    

    现在这里举个简单的例子:

    获取物品的第一个动作,然后是在商店中设置物品的动作:

    //actions.js

    const setItems = (payload)=>({type:SET_ITEMS,payload})
    
    export const fetchItem = ()=>{
    return dispatch =>{
    axios.get("/items").then(response=> 
    dispatch(setItems(response.data))).catch(error=>throw error)
      }
    }
    

    //reducer.js

    const state = {items:[]}
    
    export default function todosReducer(state = initialState, action) {
      switch (action.type) {
        case "SET_ITEMS":
          return {
            ...state,
            items: payload
          };
        default:
          return state;
      }
    }
    

    现在我们从 react 组件中获取 mount 上的项目:

    import React,{useEffect} from "react"
    import {useDispatch,useSelector} from "react-redux"
    import {fetchItems} from "action.js"
    
    const Items = ()=>{
    const items= useSelector(state=>state.items)
    const dispatch = useDispatch()
    useEffect(()=> dispatch(fetchItems()),[])
    
    return items?items.map(item =><p key={item.name}>{item.name}</p>):<p>items not available</p>
    

    希望这是您正在寻找的。​​p>

    【讨论】:

    • 在我使用 promiseMiddleWare 进行异步之前非常感谢为我完成它,但 thunk 似乎真的很简单。
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2020-01-30
    • 2023-03-20
    • 2019-08-26
    • 2021-11-01
    • 2019-11-08
    • 1970-01-01
    相关资源
    最近更新 更多