如何触发 saga 中的 fetch 调用?

How to trigger the fetch call in saga?

我创建了我的第一个 saga,但它没有被触发:

function* getData() {
  console.log("getData");
  const json = yield fetch("https://jsonplaceholder.typicode.com/users").then(
    response => response.json()
  );
  yield put({ type: "RECEIVED_DATA", json: json.data });
}

export default function* rootSaga() {
  console.log("rootSaga call");
  yield takeEvery("GET_DATA", getData);
}

如何触发 saga 调用 fetch? Codepen

这是按预期工作的项目:https://codesandbox.io/s/8l8l59wwp9

我刚刚修复了它。详细说明即将推出

首先,由于某些原因,我不知道为什么 console.log() 方法在您的项目中不起作用,您可以使用 alert() 方法代替。

其次,您的 getDate() 生成器函数应该是这样的:

function* getData() {
  console.log("getData");
  const json = yield call(() =>
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(myJson => myJson)
  );
  yield put({ type: "RECEIVED_DATA", json: json });
}

第三,在你的reducer中,我们应该得到json 属性的值而不是data 属性的action对象。

...
case "RECEIVED_DATA":
  return action.json;
...

最后,为了显示结果,我对您的代码做了一些更改:

// index.js

function render() {
  ReactDOM.render(
    <Users data={store.getState()} getData={() => action("GET_DATA")} />,
    document.getElementById("root")
  );
}

// and

// Users.js

const Users = ({ data, getData }) => (
  <div>
    hi from users
    <button onClick={() => getData()}>Get data</button>
    <ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>
  </div>
);