开发者问题收集

努力初始化初始状态并连接

2019-07-26
83

我试图用一些初始状态初始化一个 Reducer,并将其连接到一个组件,但无法解决为什么我的状态在我的组件中总是为空。

我包含了一个指向 codesandbox.io 的链接,该链接在 Reducer 中注释掉了不同的排列。

https://codesandbox.io/s/boring-hypatia-dr9c1

经过修改后的 Reducer 试图确保它至少能工作(原始版本在项目中被注释掉了):

var abilityStats = {
  strength: 18,
  dexterity: 12,
  constitution: 12,
  intelligence: 12,
  wisdom: 12,
  charisma: 13
 };

const abilityStatsReducer = (state = abilityStats, action) => {
  var stats = {}
  if(abilityStats) {
    stats.strength = {
      score: stats.strength,
      mod: calculateAbilityMod(stats.strength)
    };
    stats.dexterity = {
      score: stats.dexterity,
      mod: calculateAbilityMod(stats.dexterity)
    };
    stats.constitution = {
      score: stats.constitution,
      mod: calculateAbilityMod(stats.constitution)
    };
   stats.intelligence = {
     score: stats.intelligence,
     mod: calculateAbilityMod(stats.intelligence)
   };
   stats.wisdom = {
     score: stats.wisdom,
     mod: calculateAbilityMod(stats.wisdom)
   };
   stats.charisma = {
     score: stats.charisma,
     mod: calculateAbilityMod(stats.charisma)
   };

    return stats
  }

  return state
};

根 Reducer:

const rootReducer = combineReducers({
  abilityStats: abilityStatsReducer()
});

export default rootReducer;

Index.js

ReactDOM.render(
  <Provider store={createStore(reducers)}>
    <App />
  </Provider>,
  document.getElementById("root")
);

我正在尝试访问状态的组件在:

import React, { Component } from "react";
import { connect } from "react-redux";

class AbilityStats extends Component {
  // constructor(props) {

  //   super(props);
  //   var strength = props.abilityStats
  //   debugger;

  // }

  state = this.props.abilityStats;

  render() {
    return (
      <div>
        <div>{this.state.strength.score}</div>
        <div>test</div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  const { abilityStats } = state;
  return {
    ...abilityStats
  };
};

export default connect(mapStateToProps)(AbilityStats);

我收到错误消息

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

TypeError: Cannot read property 'strength' of null

2个回答

您需要将一个函数传递给 combineRedudcer ,而不是调用它。

const rootReducer = combineReducers({
  abilityStats: abilityStatsReducer()
});

这应该是

const rootReducer = combineReducers({
  abilityStats: abilityStatsReducer
});

在您的 mapStateToProps 中,您需要返回 abilityStats ,而不是返回它的解构。

const mapStateToProps = state => {
  const { abilityStats } = state;
  return {
    abilityStats
  };
};
Tien Duong
2019-07-26

你在 mapStateToProps 中做错了,请执行以下操作

const mapStateToProps = state => {
  return state;
};

此外,在访问状态时,你可以直接使用,

{this.props.strength}

你还在 combineReducers 中犯了一个错误,

const rootReducer = combineReducers({
  abilityStats: abilityStatsReducer // `()` not needed here
});

注意: 由于你只有一个 Reducer,你可以直接使用 Reducer 而无需 combineReducers

你可以直接导出你的 Reducer,

export default abilityStatsReducer
ravibagul91
2019-07-26