【问题标题】:how to use redux useSelector to check state and do a fetch to a database如何使用 redux useSelector 检查状态并获取数据库
【发布时间】:2022-02-14 01:30:26
【问题描述】:

我在一个项目中使用 redux,我想创建一个 useSelector 来检查 redux 状态中的值是否是默认值,如果不是,它将向数据库发出请求并更新我感觉的状态虽然它很复杂,但我很难弄清楚我需要如何做到这一点。 我需要这样做,因为有时在我正在考虑的状态中未加载正确的状态,每次我使用 useSelector 检查值是否为默认值然后从数据库中获取时都进行检查,但我更愿意编写它一种允许在 redux 选择器中处理的方式,但我无法真正掌握我需要如何做。

 const info =  useSelector(getInfo)

理想情况下,我希望在我在这里获取信息时得到处理

import { SET_USER_DETAILS } from "../constants/userConstants";

const intialState = {
  user: { },
};

const userReducer = (state = intialState, action: any) => {
  switch (action.type) {
    case SET_USER_DETAILS:
      return { ...state, user: action.payload };
    default:
      return state;
  }
};

这是我目前的 reducer 的样子,因为我发现遵循 redux 网站上的文档有点困难。

【问题讨论】:

    标签: javascript reactjs typescript asynchronous redux


    【解决方案1】:

    你可以使用 redux-thunk。 https://redux.js.org/usage/writing-logic-thunks 那么你的 thunk 可能看起来像这样:

    const thunkFunction = (dispatch, getState) => {
      // logic here that can dispatch actions or read state
    
      const currentState = getState() as typeof initialState;
      // check if state is default state
      if (JSON.stringify(initialState) === JSON.stringify(currentState)) {
        fetch(url).then(data => {
          dispatch({type: SET_USER_DETAILS, payload: data})
        })
      }
    }
    

    你需要先在 react 组件中获取数据:

    const MyComponent = () => {
      // while fetch is fetching, data will be default state,
      // and when fetch is done, that component will automatically
      // rerender with new data
      
      const data = useSelector(getInfo);
      const dispatch = useDispatch();
      
      useEffect(() => {
        dispatch(thunkFunction)
      },[])
      return <code>{JSON.stringify(data, null, 2)}</code>
    }
    

    我没有对其进行测试,因此可能需要进行一些更改 但总的来说概念是这样的

    【讨论】:

    • 感谢您的文档,在我想将逻辑从 UI 层中取出之前,我没有看到它的那一部分,所以这并不是我一直在寻找的编写方法和所有内容的方法将通过创建自定义选择器使用一个函数来处理
    • 好的。您也可以使用reselect 库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多