繁体   English   中英

如何在 redux 中动态设置初始 state 变量

[英]How to dynamically set initial state variable in redux

Im trying to set the initial state of a redux state based on an object item param straight inside the redux saga state. 它必须在这个文件中,(长话短说)所以我决定把它放在这个文件中。 所以我的第一个想法是在 redux 文件中写一个 function 来完成这项工作。 但是,不确定如何从另一个 redux 文件中访问我需要的 state。 我做了研究,发现您可以在生成器函数中使用以下语法

const state = yield select();

所以我在香草 javascript function 中尝试了这个,但正如预期的那样没有用。 有什么办法可以做到以下几点?

const initialState = {
  currentAccountId: fetchAndReturnId(),
  currentName: '',
};

function fetchAndReturnId() {
  const state = yield select();
    const { accounts } = state.global.accounts;
    const charityAccount = accounts.find(acc => acc.type === 'charity');
    return charityAccount.id;
}

只是想知道其他人是否有任何其他解决方案。 谢谢!

您可以为它制作一个 function。

这是给你的一个例子:

const initial = async () => {
  const id = await getId();
  const name = await getName();

  return {
    currentAccountId: id,
    currentName: name,
  };
};

除非你做一些高级的东西,比如注入减速器,否则你试图做的事情对我来说真的没有意义。 初始 state 被称为“初始”,因为它是在任何其他 redux 相关内容之前设置的,包括设置任何 state 或运行任何传奇。 所以一般不能根据其他的redux state来设置initialState,因为当时没有其他的state。

也就是说,您还可以做一些其他的事情。 如果您需要为多个减速器设置相同的初始 state,您可以将其提取到某个常量,然后在两个地方都使用它。

const INITIAL_DATA = 'foo';

const reducer1 = (state = INITIAL_DATA, action) => ...
const reducer2 = (state = INITIAL_DATA, action) => ...

如果它是动态的,比如从 BE 获取的数据,那么它可能不是初始的 state,而是您将在应用程序生命周期后期使用 redux 操作设置的东西。

const reducer = (state = null, action) => {
  if (action.type === 'FETCHED_DATA') return action.data
  return state
}

function * saga() {
  const data = yield fetchData();
  yield put({type: 'FETCHED_DATA', data});
}

Or if you have another saga, that needs to read existing redux state and then send it to reducer handling different part of the redux state you can use the select effect.

function * saga() {
  const data = yield select(getDataFromStateSlice1);
  yield put({type: 'STORE_DATA_IN_STATE_SLICE_2', data});
}

无论如何,由于您尝试做的事情对我来说没有意义,我可能在您的问题中遗漏了一些东西,请随时进一步详细说明。

暂无
暂无

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

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