简体   繁体   English

为什么React状态与Redux状态不同

[英]Why React state is different from Redux State

I'm new to Redux + React and Im facing a problem that it's getting me crazy. 我是Redux + React的新手,我正面临一个让我发疯的问题。

Update: Added Git repo instead of pasting here all the code 更新:添加了Git存储库,而不是在此处粘贴所有代码

I'm creating a simple darts scoreboard and saving everything on the redux store. 我正在创建一个简单的飞镖记分牌,并将所有内容保存在redux商店中。 The problem is that when I try to access the data from a render method is not there. 问题是当我尝试从render方法访问数据时不存在。 Is like state not being propagated to props. 就像状态没有传播到道具上一样。

But if I check redux developments tools the data is there. 但是如果我检查redux开发工具,数据就在那里。 Some screenshots to clarify, where you can see that while in Redux all shots are there on React only the first shot appear. 需要澄清一些屏幕截图,您可以在其中看到在Redux中所有镜头都在React上出现,仅显示第一个镜头。 所有照片的Redux商店 反应状态丢失的镜头

I thought that could be due to my reducers not using inmutable data but I think they are all ok. 我认为这可能是由于我的化简器没有使用不变的数据,但我认为它们都可以。 Code Im using below: 使用以下代码Im:

import update from 'react-addons-update';

function players(state = [], action) {

  switch( action.type ){

    case 'ADD_USER_TO_GAME':
        return [
            ...state,
            action.user
        ];
    case 'REORDER_USERS':
      return action.sortedArray;

    case 'REMOVE_USER':
      return [
        ...state.slice( 0, action.index ),
        ...state.slice( action.index + 1 ),
      ];

    case 'SET_ALL_SCORE':
      let new_state = [...state];
      for( let player in new_state ){
          if( new_state[player].ID ) {
              new_state[player].score = action.user_score;
              new_state[player].shots = [];      
          }
      }
      return new_state;

    case 'SAVE_SHOT':
      return [
        ...state.slice( 0, action.user ),
        { ...state[action.user], shots: [...state[action.user].shots, action.shot] },
        ...state.slice( action.user + 1 ),
      ];

    case 'SAVE_SCORE':

      return [
        ...state.slice( 0, action.user ),
        { ...state[action.user], score: action.score },
        ...state.slice( action.user + 1 ),
      ];

    default:
        return state;
  }

}

export default players;

You're mutating your state directly here: 您直接在这里更改状态:

case 'SET_ALL_SCORE':
  let new_state = [...state];
  for( let player in new_state ){
      if( new_state[player].ID ) {
          new_state[player].score = action.user_score;
          new_state[player].shots = [];      
      }
  }
  return new_state;

You did clone the state object, but you're mutating it's members directly. 您确实克隆了状态对象,但直接对其成员进行了突变。

Like this: 像这样:

case 'SET_ALL_SCORE':
  return state.map(player => (
    player.ID
      ? { ...player, score: action.user_score, shots: [] }
      : player
  ));

You are most likely not including the Provider from react-redux in your index.js file. 您很可能不在index.js文件中包括来自react-redux的提供程序。 The Provider gives you access to the store in each component. 提供程序使您可以访问每个组件中的商店。 Check out the below example: 查看以下示例:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import rootReducer from './reducers/rootReducer'
import {createStore, applyMiddleware} from 'redux';
import reduxPromise from 'redux-promise';
import { Router, browserHistory } from 'react-router';
import Routes from './routes';


let storewithmiddleware = applyMiddleware(reduxPromise)(createStore)(rootReducer)

ReactDOM.render(
  <Provider store={storewithmiddleware}>
    <Router history={browserHistory} routes={Routes} />
  </Provider>,
  document.getElementById('root')
);

Additionally, you will want to mapStateToProps and subscribe the component to the store with connect() like this: 此外,您将需要mapStateToProps并使用connect()将组件订阅到商店中,如下所示:

const WelcomePageContainer = connect(mapStateToProps, null)(WelcomePage)

function mapStateToProps(state) {
  return {currentUser: state.currentUser}
} 

(see here: http://redux.js.org/docs/basics/UsageWithReact.html ) (请参见此处: http : //redux.js.org/docs/basics/UsageWithReact.html

It seems like you could really benefit from going through Dan Abramov's tutorials on Redux on egghead.io They are fantastic and clear. 似乎可以从egghead.io上的Dan Abramov关于Redux的教程中真正受益,它们很棒而且清晰。 Also, do the code along tutorials--they give a great sense of how Redux layers on top of your React app. 另外,按照教程中的代码进行操作-他们可以很好地了解Redux如何在React应用程序之上分层。

Just to note: component state in React is not synonymous with the Redux store. 请注意:React中的组件状态与Redux存储不是同义词。

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

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