在reducer func中获取api数据

问题描述 投票:0回答:1

按照第 23 行的承诺获得输出

我正在尝试使用 usereducer 来获取数据,其中的调度程序函数在 useeffect hook 内被调用。但是我得到的输出是承诺要做什么?

let initApi=null;
let apiReducer=async (curdata,perform)=>{
    if(perform=='fetch'){
        fetchData();
    }else{
        return null;
    }
}

function Cloth() {
    let [clothapiData,apiDispatcher]=useReducer(apiReducer,initApi);
    useEffect(
        ()=>{
        apiDispatcher('fetch')
        }
    ,[])
    console.log(clothapiData);
    return (
    <div className='cloths'>
    {<video autoPlay src='../assets/22.gif'></video>}
    { clothapiData?clothapiData.map(({id,image,title,price})=>{
        return <NavLink to={`../../${id}`} className='cloth' key={id}>
            <div><img src={image} alt="" /></div>
            <h1>{title}</h1>
            <h4>₹{price}</h4>
        </NavLink>
    }): <h1>Loading...</h1> }
    </div>
    )
}
javascript reactjs react-native react-hooks
1个回答
0
投票

一般来说,“reducer”函数应该被视为纯粹的、同步的函数,而你的函数两者都不是。

运行在

useEffect
钩子 中获取一些数据的副作用,然后 将操作负载分派到您的减速器。

实施示例:

const initialState = null;

const apiReducer = (state, action) => {
  switch(action.type) {
    case "setData":
      return action.payload;
    default:
      return state;
  }
}

const setData = (payload) => ({
  type: "setData",
  payload,
});

function Cloth() {
  const [clothApiData, apiDispatcher] = useReducer(apiReducer, initialState);

  useEffect(() => {
    fetchData()
      .then(data => {
        apiDispatcher(setData(data));
      })
      .catch(error => {
        // catch and handle/ignore any rejections or thrown errors
      });
  }, []);

  return (
    <div className='cloths'>
      <video autoPlay src='../assets/22.gif' />
      {clothApiData
        ? clothApiData.map(({ id, image, title, price }) => (
          <NavLink to={`../../${id}`} className='cloth' key={id}>
            <div><img src={image} alt="" /></div>
            <h1>{title}</h1>
            <h4>₹{price}</h4>
          </NavLink>
        ))
        : <h1>Loading...</h1>
      }
    </div>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.