无法显示来自减速器的消息

时间:2017-06-21 11:21:34

标签: reactjs react-redux

我尝试将message 'hello brozz..'从reducer显示为组件render()方法。ComponentDidMount()this.props.message显示为please see the image。我的减速机就像

 export const geod = (state ={}, action) => {
      console.log('inside reducer');
        switch(action.type){


            case 'INITIAL_MESSAGE':

              return [
                        ...state, {
                          message:'hello brozz..'
                        }
                      ]
            case 'CLICK_MESSAGE':
                  return [ 
                            ...state, { 
                                            message: ''
                                      }
                          ]
            default:
                    return state;
        }

     };

但我不能在渲染方法中使用this.props.message作为<div><div>{this.props.message}</div></div>。我收到了错误

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons

我的组件是,

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { initialMessageAction, clickButtonAction } from './redux.js';
import { connect } from 'react-redux';
import { Message } from './messageComponent';

class App extends Component {

  componentWillMount() {
    console.log('component will mount');
    let data = this.props.initialMessageAction();
  }
  componentDidUpdate() {
    console.log('comp Did Update')
    console.log(this.props.message)
  }
  render() {

    return (
      <div className="App">
        <div className="App-header">        
        </div>
        <p className="App-intro">
        react-redux-data-flow
        </p> 
              <div>{this.props.message}</div>
             <div>{this.props? <div>hi ..<button onClick={ () => this.props.clickButtonAction() }>hide message</button></div>: ''}</div>
      </div>
    );
  }
}


    const mapStateToProps = (state, ownProperty) => ({ 

    message:state.geod,   


  });   

   const mapDispatchToProps =  { 

     initialMessageAction,
    clickButtonAction

  } 

  export default connect(
                             mapStateToProps,
                             mapDispatchToProps

                    )(App);

1 个答案:

答案 0 :(得分:0)

const initialState = {message: null};
 export const geod = (state = initialState, action) => {
      console.log('inside reducer');
        switch(action.type){
            case 'INITIAL_MESSAGE':
                return Object.assign({}, state, {message:'hello brozz..'});
            case 'CLICK_MESSAGE':
                return Object.assign({}, state, {message: ''}); 
            default:
                return state;
        }

     };

stateMap { message: state.geod.message }

作为初始状态您使用空对象并且看错了。