简体   繁体   English

从Redux迁移到React Context API +钩子时如何处理副作用

[英]How to handle side effects when migrating from Redux to React Context API + hooks

If you have a Redux Application which you'd like to migrate to the new React Context API + hooks (useReducer) how would you replace redux-saga or redux-thunk for handling side effects? 如果您有要迁移到新的React Context API +钩子(useReducer)的Redux应用程序,您将如何替换redux-saga或redux-thunk来处理副作用? Let's take the example from redux-saga's github page: 让我们以redux-saga的github页面为例:

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

function* mySaga() {
  yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}

export default mySaga;

What is the recommended best practice for doing the equivalent without Redux, but using the React Context api + hooks instead? 在不使用Redux的情况下进行等效操作的建议最佳实践是什么,而是使用React Context api +钩子代替?

Take a look at useEffect hook. 看一下useEffect挂钩。 This is what you use for side-effects. 这就是您使用的副作用。

https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-effect.html

Here is an example of how to call an api from your component and render the data: 这是如何从组件调用api并呈现数据的示例:

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import axios from "axios";

function SearchResults() {
  const [data, setData] = useState(null);
  useEffect(() => {
    function getFetchUrl() {
      return "https://hn.algolia.com/api/v1/search?query=react";
    }
    async function fetchData() {
      console.log("asdasd");
      const result = await axios(getFetchUrl());
      setData(result.data);
    }

    fetchData();
  }, []);
  return <div>{JSON.stringify(data)}</div>;
}

ReactDOM.render(<SearchResults />, document.getElementById("root"));

I partially took this code from overreacted.io, I strongly suggest you read this amazing article about useEffect hook: https://overreacted.io/a-complete-guide-to-useeffect/ 我从overreacted.io中部分获取了此代码,强烈建议您阅读有关useEffect挂钩的这篇奇妙文章: https : useEffect

Regarding useReducer , it's basically a useState on steroids. 关于useReducer ,它基本上是类固醇上的useState It allows you to handle more complex state operations, but there isn't a big difference really. 它允许您处理更复杂的状态操作,但实际上并没有太大的区别。

In the case you want state to be shared by different components, you may use useContext but its really unrelated on how the side-effects work. 如果您希望状态由不同的组件共享,则可以使用useContext但它与副作用的工作方式实际上无关。

---- about redux: ----关于redux:

I just want to comment also that moving to use React Context api + hooks to replace redux in your app could be good if you just use it for passing data to nested components, for example. 我只想评论一下,例如,如果仅使用它来将数据传递给嵌套组件,那么在应用程序中使用React Context api +钩子替换redux可能会很好。 But if you want all the great tooling, middleware, devtools, etc, Redux is still a great choice, even with hooks, they are not mutually exclusive. 但是,如果您需要所有出色的工具,中间件,devtools等,则Redux仍然是一个不错的选择,即使使用钩子,它们也不是互斥的。

See: 看到:

https://blog.isquaredsoftware.com/2019/03/presentation-state-of-redux/ Specifically https://blog.isquaredsoftware.com/presentations/2019-03-state-of-redux/#/10 https://blog.isquaredsoftware.com/presentations/2019-03-state-of-redux/#/11 https://blog.isquaredsoftware.com/2019/03/presentation-state-of-redux/特别是https://blog.isquaredsoftware.com/presentations/2019-03-state-of-redux/#/10 https: //blog.isquaredsoftware.com/presentations/2019-03-state-of-redux/#/11

If you have a Redux Application which you'd like to migrate to the new React Context API, you need to be able to get data to any component in your hierarchy, you need to be able to separate your view logic from your business logic and you need to be able to split up the business logic, meaning modularity, meaning not have 1000 LOCs in a single file. 如果您有要迁移到新的React Context API的Redux应用程序,则需要能够将数据获取到层次结构中的任何组件,并且需要能够将视图逻辑与业务逻辑分开,并且您需要能够拆分业务逻辑,即模块化,即单个文件中没有1000个LOC。

Unless you have no other choice, I would stick with Redux. 除非您别无选择,否则我会坚持使用Redux。 With Redux you get excellent documentation, the docs are pretty well written and you can generally understand whats going on. 使用Redux,您可以获得出色的文档,文档写得很好,并且您通常可以了解发生了什么。 The design patterns are well-known and their is enough support and open-source libraries specifically made to work with Redux. 设计模式是众所周知的,它们已经足够支持和专门为与Redux一起使用而设计的开源库。

With Context, you don't have to use a separate library, that's about it. 使用Context,就不必使用单独的库了。 That's the only benefit to using Context in place of Redux. 这是使用Context代替Redux的唯一好处。 Context has its own challenges because of cross-cutting concerns when building the store. 由于在建立商店时存在跨领域关注点,因此上下文有其自身的挑战。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM