React Hooks,useReducer无法获取状态

时间:2018-11-01 22:28:23

标签: reactjs react-hooks

我正在使一个简单的组件尝试利用useEffect和useReducer挂钩。除了数组中的所有项均未真正进入组件之外,其他所有内容似乎都正常运行。我已经在各种函数中完成了一些console.log语句,并且可以看到API调用成功,并且在事件下该函数的范围内有可用数据。但是,所有呈现的都是一个空盒子。我的代码是:

import React, { useReducer, useEffect } from "react";
import "./App.css";

const  App = () => {
  const [events, dispatch] = useReducer(
      (state, action) => { switch (action.type) {
          case "fetchEvents":
              state = [ ...state, action.data];
             return state;

            case "removeEvent":
              return state.filter((_, idx) => idx !== action.idx);

            default:
                console.log(state);
              return state;
        }
      },
  []);

  useEffect(async () => {
    const response = await fetch("https://easynode-veohkvapci.now.sh/api/test");
    const data = await response.json();
    dispatch({type: "fetchEvents", data});
  },[]);

  console.log(events, 'log events');

  return (
      <div>
          {events.map((event, idx) => (
              <div key={event.event_url} style={{ border: "solid" }}>
                  <p>{event.name}</p>
                  <p>{event.date}</p>
                  <p>{event.description}</p>
                <button onClick={() => dispatch({ type: "removeEvent", idx})}>Remove Event</button>
              </div>
          ))}
      </div>
  );
};

export default App;

我应该在useReducer内部调用useEffect吗?我可能正在搞砸本应以异步方式发生的事情。

1 个答案:

答案 0 :(得分:2)

从请求中获得的数据是一个数组,因此您需要确保在化简器的fetchEvents情况下也将其分布。

const [events, dispatch] = useReducer((state, action) => {
  switch (action.type) {
    case "fetchEvents":
      state = [...state, ...action.data];
      return state;

    case "removeEvent":
      return state.filter((_, idx) => idx !== action.idx);

    default:
      return state;
  }
}, []);