减速器减少后状态不会更新

时间:2017-07-19 09:26:47

标签: reactjs react-redux

我正在尝试在页面加载时更新我的​​DOM。基本上它应该显示用户渲染的数据。但是当我通过记录器检查时,我发现值没有存储在my.props值中。但行动被触发,减速器完成了它的任务。所以我担心为什么我的mapStatToProps没有更新?  这是我的容器文件

import User from "../components/User"
import React from "react"
import {connect} from "react-redux"
import {fetchUsers} from "../action/UserAction"
import PropTypes from 'prop-types'


const UserContainer =React.createClass ( { 
    componentWillMount(){
    console.log("componenet will mount")
    this.props.dispatch(fetchUsers());

},

render(){
console.log(this.props);
    return(
     <User
    name={this.props.users[0].name}
    role={this.props.users[0].role}>
    </User>
    )
}
})

UserContainer.propTypes = {
users:PropTypes.arrayOf(PropTypes.shape({
    name:PropTypes.string.isRequired,
    role:PropTypes.string.isRequired
})).isRequired
}

const mapStateToProps= state => {
    console.log("state",state)
    return{
    users:state.users
    }
}
export  default connect(
    mapStateToProps
)(UserContainer)

我的reducer文件

export default function reducer(state={users :[]},action){
   // console.log("inside reducer")
   switch(action.type){
       case "FETCH_USERS":{

           const newState={...state,users:action.payload}
           console.log("newSrate",newState)
           return newState
       }
        default: {
  return {
    ...state
  }
        }
}
}

和我的操作文件

export function fetchUsers(){
    console.log("fetch users")
    return {
        type:"FETCH_USERS",
        payload:"[{'name':'x','roles':'developer'},{'name':'y','role':'god'}]"

    }
}

我收到类似name is not defined for users的错误,因为当我检查this.props用户是空数组

2 个答案:

答案 0 :(得分:1)

问题是你的初始状态是:

state={
  users : []
}

在第一次渲染中,您尝试访问this.props.users[0].namethis.props.users[0]undefined,它将触发并发生错误。
像这样更新您的组件:

import User from "../components/User"
import React from "react"
import {connect} from "react-redux"
import {fetchUsers} from "../action/UserAction"
import PropTypes from 'prop-types'


const UserContainer =React.createClass ( { 
    componentWillMount(){
    console.log("componenet will mount")
    this.props.dispatch(fetchUsers());

},

render(){
    if (!this.props.users.length) return null; // return null if there are no users in the array

    return(
     <User
    name={this.props.users[0].name}
    role={this.props.users[0].role}>
    </User>
    )
}
})

UserContainer.propTypes = {
users:PropTypes.arrayOf(PropTypes.shape({
    name:PropTypes.string.isRequired,
    role:PropTypes.string.isRequired
})).isRequired
}

const mapStateToProps= state => {
    console.log("state",state)
    return{
    users:state.users
    }
}
export  default connect(
    mapStateToProps
)(UserContainer)

答案 1 :(得分:-1)

在尝试在屏幕上显示数据之前,应确保正确加载数据。 如果您的案例不涉及异步请求并将其与redux-think或类似请求结合使用,您只需在组件中尝试此操作:

if( !users ) {
  return (...loading ...);
}
return (Your content here);