【问题标题】:Why is reducer failing to update the store?为什么reducer无法更新商店?
【发布时间】:2019-04-08 04:17:07
【问题描述】:

在我看来,我的组件、动作创建器和减速器都设置正确,但由于某种原因,当我移动滑块时,我的商店没有更新。

这是我的没有导入的 App.js 文件

class App extends React.Component {
  state = {
    value: 100,
  };

  handleChange = (event, value) => {
    this.setState({ value });
    console.log(value)
    this.props.dispatch(PriceFilter(value))
  };

  render() {
    console.log(this.props)

    return (
      <div style={styles.root}>
        <Slider
          value={this.state.value}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return { price: state.reducers }
}

export default connect(mapStateToProps)(App)

我的动作超级简单

export const PriceFilter = (price) => ({
    type: 'PRICE_FILTER',
    price: price
})

我的reducer也很基础:

const initialState = {
    price: 10000
}

const priceReducer = (state = initialState, action) => {
    switch(action.type) {
        case 'PRICE_FILTER':
            return {
                ...state,
                price: action.price
            }
        default:
            return state
    }
}

export default priceReducer

有人知道我做错了什么吗?

【问题讨论】:

  • yiu 是否尝试在 action creator 和 reducer 中添加 console.log?
  • 是的,它返回了正确的值......这缩小了范围。奇怪的是该值被返回为未定义。即使我在安慰它时可以看到它。
  • 请将 console.log 调用添加到您发布的代码中,并指出该值的打印位置和未定义的位置。
  • 想通了,它在我的 mapStateToProps 中应该是这个。 const mapStateToProps = (state) => { return { price: state.price } }

标签: reactjs redux


【解决方案1】:

通过console 检查您的redux 状态是否即将到来。我认为如果您没有在 redux 中使用 combineReducers 方法,那么您的 redux 商店仅来自 state

const mapStateToProps = (state) => {
  console.log(state) // check redux store
  return { price: state.reducers }
}

【讨论】:

    【解决方案2】:

    我需要将 mapStateToProps 更改为:

    const mapStateToProps = (state) => {
    return { price: state.price }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 2020-12-18
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多