简体   繁体   English

无法将道具传递给 react-redux 中的组件

[英]unable to pass props to components in react-redux

I'm trying to pass props to multiple components using react-redux.我正在尝试使用 react-redux 将道具传递给多个组件。 The data that I'm receiving and trying to pass is from a database, so asynchronicity is involved.我接收并尝试传递的数据来自数据库,因此涉及异步性。 Because props isn't defined when it hits the component, my app is throwing an undefined error.因为 props 在碰到组件时没有定义,所以我的应用程序抛出了一个未定义的错误。 After it throws the error in the component, it continues to resolve state, but Once state is defined, it doesn't rerender the component with the new props.在组件中抛出错误后,它会继续解析状态,但是一旦定义了状态,它就不会使用新的 props 重新渲染组件。 Another nugget...I'm using combineReducers.另一个金块……我正在使用 combineReducers。 Before using combineReducers (just using the baby-reducer) I didn't have this problem.在使用 combineReducers (仅使用婴儿减速器)之前,我没有这个问题。 It started after I made another reducer and combined it with (baby-reducer) Any idea what is going on here?它是在我制作另一个减速器并将其与(婴儿减速器)结合之后开始的。知道这里发生了什么吗? Why won't my component re-render?为什么我的组件不会重新渲染?

Here is my container that is rendering components:这是我正在渲染组件的容器:

    import React,{Component} from 'react'
    import store from '../store'
    import {connect} from 'react-redux';
    import BabyProfile from '../components/BabyProfile'
    import Weight from '../components/Weight'
    import Height from '../components/Height'
    import Feed from '../components/Feed'
    import Sleep from '../components/Sleep'
    import Diaper from '../components/Diaper'


    class BabyProfileContainer extends Component {

      render(){
        // console.log("RENDER PROPS", this.props)
        const  {baby, weight, height, feed, sleep, diapers} = this.props

        return(
          <div>
            <BabyProfile baby={baby}/>
            <Weight weight={weight}/>
            <Height height={height}/>
            <Feed  feed={feed}/>
            <Sleep sleep={sleep}/>
            <Diaper diapers={diapers}/>
          </div>
        )
      }
    }

    const mapStateToProps = (state, ownProps) => {
      // console.log("MSTP Baby Container", state, "OWN PROPS", ownProps)
      return {
        baby: state.baby,
        diapers: state.diapers,
        weight: state.weight,
        height: state.height,
        sleep: state.sleep,
        feed: state.feeding
      }
    }



    export default connect(mapStateToProps)(BabyProfileContainer)

here is my baby-reducer:这是我的婴儿减速器:

    import {RECEIVE_BABY} from '../constants'


    const initialBabyState = {
      baby: {},
      diapers: [],
      weight: [],
      height: [],
      feeding: [],
      sleep: []

    }

    export default function(state = initialBabyState, action){
    console.log('BABY REducer')

    const newState = Object.assign({}, state)

       switch (action.type){

         case RECEIVE_BABY:
         newState.baby = action.baby;
         newState.diapers = action.diapers
         newState.weight = action.weight;
         newState.height = action.height;
         newState.feeding = action.feeding;
         newState.sleep = action.sleep

         break;




         default:
          return state

       }
       return newState

    }

here is my combinedReducer:这是我的组合减速器:

    import {combineReducers} from 'redux'
    import baby from './baby-reducer'
    import parent from './parent-reducer'



    export default combineReducers({
      baby,
      parent

    })

Here is my weight component:这是我的重量分量:

    import React from 'react';
    import {Line} from 'react-chartjs-2'


    export default function(weight){


    console.log("IN WEIGHT", weight)
    var weightArr = weight.weight

    const weightData = {
      labels: weightArr.map(instance=>instance.date.slice(0,10)),
      datasets:[{
        label: "baby weight",
        backgroundColor: 'rgba(75,192,192,1)',
        data: weightArr.map(instance =>(instance.weight))
      }]
    }

    const options ={

        maintainAspectRatio: false,
        xAxes: [{
          stacked: true,
                  ticks: {
                      beginAtZero:true
                  }
              }],
        yAxes: [{ticks: {
            beginAtZero:true
        }
        }]
      }



    return (
      <div className="baby">
        <div>
          <h3>I'm In weight component</h3>
        </div>
        <div className="weight"></div>
        {
        weightArr.map((weight,index) => (
          <div key={index}>
            <span>{ weight.weight}</span>
          </div>
        ))

      }
      <div className="Chart">
        <Line data={weightData} width={200} height={200} options={options}/>
      </div>
      </div>
    );
    }

Here is my action creator:这是我的动作创建者:

    import {RECEIVE_BABY} from '../constants'
    import axios from 'axios'



    export const receiveBaby = (baby,weight,height,sleep,diaper,feeding) =>({
      type: RECEIVE_BABY,
      baby: baby,
      weight: weight,
      feeding: feeding,
      height: height,
      sleep: sleep,
      diapers: diaper

    })



    export const getBabyById = babyId => {
      console.log("GET BABY BY ID")
      return dispatch => {
        Promise
          .all([
            axios.get(`/api/baby/${babyId}`),
            axios.get(`/api/baby/${babyId}/weight`),
            axios.get(`/api/baby/${babyId}/height`),
            axios.get(`/api/baby/${babyId}/sleep`),
            axios.get(`/api/baby/${babyId}/diaper`),
            axios.get(`/api/baby/${babyId}/feed`)
          ])
          .then(results => results.map(r => r.data))
          .then(results => {
            console.log("THIS IS RESULTS in Action assadkjasdfkjl;", results)
            dispatch(receiveBaby(...results));
          })
          .catch(function(err){
            console.log(err)
          })
      };
    };

Here is a snapshot from chrome devTools of the error and the subsequent state这是错误和后续状态的 chrome devTools 快照

any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!谢谢!

I believe this is linked to the fact that when you combine the reducers you need to include them in the mapStateToProps in the following way:我相信这与以下事实有关:当您组合减速器时,您需要通过以下方式将它们包含在mapStateToProps中:

const mapStateToProps = (state, ownProps) => {
      // console.log("MSTP Baby Container", state, "OWN PROPS", ownProps)
      return {
        baby: state.parent.baby,
        diapers: state.parent.diapers,
        ...
      }
    }

Basically, you have to make sure the appropriate reducer is connected here.基本上,您必须确保此处连接了合适的减速器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM