【问题标题】:How to display the value of state in react-reduxreact-redux如何显示state的值
【发布时间】:2019-01-15 16:35:08
【问题描述】:

我有一个正在使用 react-redux 开发的功能计数器应用程序。每次使用 Increment/Decrement 函数调度操作时,我都可以看到状态更新,但是,我无法实际输出状态的值。

这是我第一次尝试使用模块构建 redux 应用程序(而不是使用 redux cdn 构建 html 文件)。请帮我弄清楚我做错了什么。

谢谢。


//App.js

import { Increment, Decrement } from './redux'

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>{this.props.count}</h1> //Doesn't output anything
        <button onClick={this.props.Increment}>+</button>
        <button onClick={this.props.Decrement}>-</button>
      </div>
    );
  }
}

const mapStateToProps = state => ({
    count: state.count
})

const mapDispatchToProps = {
    Increment,
    Decrement
}

const AppContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(App)

export default AppContainer

//redux.js 

import { createStore } from 'redux';

export const Increment = () => {
    return {
        type: 'INCREMENT'
    }
}

export const Decrement = () => {
    return {
        type: 'DECREMENT'
    }
}


export const reducer = (state = 0, action) => {
    switch(action.type){
        case 'INCREMENT':
        return state + 1

        case 'DECREMENT':
        return state - 1

        default:
        return state
    }
}


export function configureStore(intitalState = 0){
    const store = createStore(reducer, intitalState)
    return store;
}

export const store = configureStore()

//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import { Provider } from 'react-redux';
import { store } from './redux';
import AppContainer from './App';

ReactDOM.render
(<Provider store={store}>
    <AppContainer/>
</Provider>, document.getElementById('root'));



【问题讨论】:

  • 您是否尝试过在mapStateToProps 中记录您的状态?我看到你打电话给state.count,但count 不是你的减速机之一。因此,您的值存储为 state 本身。但是,请尝试记录状态以查看这是否正确。

标签: reactjs redux react-redux


【解决方案1】:

在这种情况下,state 实际上是一个值,而不是一个将值存储为count 属性的对象。

应该是:

const mapStateToProps = state => ({
    count: state
})

或者combineReducers可以用来映射特定reducer作为store属性:

const store = createStore(combineReducers({count: reducer }), intitalState)

【讨论】:

  • 非常感谢!我完全错过了这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2019-02-09
  • 2018-12-04
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
相关资源
最近更新 更多