简体   繁体   English

使用 React+Redux 从数据库中设置 initialState 值

[英]Set initialState values from database with React+Redux

I tried to set input value in redux form and I figure out that my state don't have user values.我试图在 redux 表单中设置输入值,我发现我的 state 没有用户值。 Just the default one that inserted like that:只是这样插入的默认值:

import { Map, fromJS } from 'immutable';
import { INIT } from '../../actions/actionConstants';

const initialState = {
  usersLogin: Map(
      {
    id: '',
    name : 'test',
    email: 'test01@gmail.com',
    password: 'test',
    remember: true
  }

  )
};
const initialImmutableState = fromJS(initialState);
export default function reducer(state = initialImmutableState, action = {}) {
  switch (action.type) {
    case INIT:
      return state;
    default:
      return state;
  }
}

How I am able to get in const all user values that are in the database?我如何能够在 const 中获取数据库中的所有用户值?

Same way as anything else, but you'll need it to be synchronous if implemented as your snippet.与其他任何方法相同,但如果实现为您的代码片段,您将需要它是同步的。

FWIW, I almost always have the DB state load async, because DB calls can fail. FWIW,我几乎总是让 DB state 异步加载,因为 DB 调用可能会失败。 I always have a hard-coded fallback then set the state once the DB (or API/etc) async call completes.我总是有一个硬编码的后备,然后在 DB(或 API/等)异步调用完成后设置 state。

Also, in general, general "app user" stuff I keep fairly high up in the store since it's required almost everywhere, so on login/etc.此外,一般来说,我在商店中保持相当高的一般“应用程序用户”东西,因为它几乎无处不在,所以登录/等。 I set it and by the time it's needed anywhere it's pretty much always available--but in the event of an async failure the fallback is always required.我设置了它,当它在任何地方需要时,它几乎总是可用的——但在异步失败的情况下,总是需要回退。

(Unrelated, but there's no reason to have separate cases in this... uh... case.) (不相关,但没有理由在这个......呃......案件中有单独的案例。)

You need to do couple of things here你需要在这里做几件事

1- You need to write an action creator which does this API fetching for you and then dispatch an action with the API response let's say SET_DB_VALUES 1-您需要编写一个动作创建器,它会为您执行此 API 获取,然后使用 API 响应发送一个动作,比如说 SET_DB_VALUES

2- Then you need to dispatch this action, you can do it in the componentDidMount of your Redux root element (the one that is wrapped by Provider and receives the store) 2-然后您需要调度此操作,您可以在 Redux 根元素的 componentDidMount 中执行此操作(由 Provider 包装并接收存储的那个)

3- Change your reducer to listen to this action like 3-改变你的减速器来听这个动作,比如

switch (action.type) {
case INIT:
  return state;
case SET_DB_VALUES:
  return {
     ...state,
     action.payload
  }
default:
  return state;

} }

Note: You will need to use some middleware to do asynchronous calling in action creator, You can use Thunk,注意:您将需要使用一些中间件来执行操作创建者中的异步调用,您可以使用 Thunk,

Hope it helps you starting希望它可以帮助你开始

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

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