javascript React,Redux,响应数据如何在所有组件中可用?

4nkexdtk  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(99)

我使用react和redux,API返回数据。在useDispatch中写入的数据如何在其他组件中可用。
customerId如何在所有组件中可用。我创建了一个调用API的代码,并在响应中返回数据。我还创建了一个减速器。不知道如何做到这一点,使customerId将是可用的。

{

    "sessionId": "5f9f0de7-c7b3-3029",
    "customerId": "410742",
    "recepientId": "122",

    "keyPropertiesList": [
        {
            "id": 267076,

            "properties": {

                "customer1": {

                    "firstName": "test",

                    "lastName": "A",

                    "fullName": "test A”

                },

                "userDetail": {

                    "userId": "3770930",

                    "name": "Sam"

                },

                "locationID": "03144"

            }

        }

    ],

    "timeStamp": "2023-05-19T06:12:32Z"

}
const test = () => {
  const [sessionInfo, setsessionInfo] = useState(useSelector(state => state.app.DataReducer.sessionDetails));

  const uDispatch = useDispatch();

  useEffect(() => {
    sessionInformation();

    async function sessionInformation() {
      const session_ID = '5f9f0de7-c7b3-3029'

      console.log("sessionInformaiton: " + session_ID)

      await SessionInformationService({ sessionId: session_ID })
        .then((result) => {
          console.log("Result: " + JSON.stringify(result));

          if (result.data !== undefined) {
            setsessionInfo(result.data);
          }
        });
    }

    uDispatch(types.updateData({
      sessionDetails: {
        customerId: sessionInfo.customerId,
          customerfirstName: sessionInfo.firstName,
          customerlastName: sessionInfo.lastName,
          customerfullName: sessionInfo.fullName,
        }
      })
    );
  }, []);

  return (
    <>

    </>
  )
};

export default test;

还原剂

import * as types from './action';

export const initialState = {
  sessionDetails: {
    customerId: '',
    customerfirstName: '',
    customerlastName: '',
    customerfullName: ''
  }
}

const Datareducer = (state = initialState, action) => {
  switch (action.type) {
    case types.UPDATE_DATA:
      const output = action.payload;

      if (output.sessionDetails) {
        state.sessionDetails = output.sessionDetails;
      }

      return {
        ...state,
      }
      break;

    default:
      return state;
  }
}

export default Datareducer;

action.js

export const UPDATE_DATA = 'UPDATE_DATA';

export const updateData = payload => ({
  type: UPDATE_DATA,
  payload
});
wn9m85ua

wn9m85ua1#

要解决的第一个问题是reducer函数中的状态突变。
state.sessionDetails = output.sessionDetails;改变当前状态对象。浅复制先前的状态引用 *,然后 * 覆盖属性。有关详细信息,请参见Immutable Update Patterns

const dataReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.UPDATE_DATA:
      const { sessionDetails } = action.payload;

      if (sessionDetails) {
        return {
          ...state,
          sessionDetails: {
            ...state.sessionDetails,
            ...sessionDetails,
          }
        };
      }

      return state;

    default:
      return state;
  }
};

第二个问题是Test组件不能正确地管理获取数据和更新存储。它在sessionInfo本地状态变量中缓存来自redux的sessionDetails状态的副本,但useEffect同时获取会话数据 * 和 * 调度updateData操作,该操作只是将未更新的sesstionInfo本地状态发送回存储。实际上,Redux状态不会使用填充的数据进行更新。
不需要本地的sessionInfo状态,useEffect直接挂接、获取和分派数据。
React组件也使用PascalCase名称,test不是有效的React组件,但Test是。重命名功能组件。

const Test = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const sessionInformation = async () => {
      const sessionId = '5f9f0de7-c7b3-3029';

      console.log("sessionInformaiton: ", sessionId);

      try {
        const { data } = await SessionInformationService({ sessionId });

        console.log("Result: ", { data });

        if (data) {
          const userData = {
            sessionDetails: {
              customerId: data.customerId,
              firstName: data.customerfirstName,
              lastName: data.customerlastName,
              fullName: data.customerfullName,
            }
          };

          dispatch(types.updateData(userData));
        }
      } catch (error) {
        // handle any errors, if necessary, or ignore, your call
      }
    };
 
    sessionInformation();
  }, []);

  return (
    <>
      ...
    </>
  );
};

export default Test;

使用useSelector钩子访问状态。选择器函数遵循通过组合归约器形成的状态结构。
示例:

import { useSelector } from 'react-redux';

...

const SomeComponent = () => {
  const { customerId } = useSelector(
    state => state.app.DataReducer.sessionDetails
  );

  ...
};

相关问题