【问题标题】:mapStateToProps always returns undefined in Redux despite initialized尽管已初始化,但 mapStateToProps 在 Redux 中始终返回 undefined
【发布时间】:2017-02-24 07:18:43
【问题描述】:

我正在尝试从reducer(下面的footerreducer.js)返回mapStatetoProps(下面的FooterLink.js)中未定义的状态。

我现在只在 mapStatetoProp 函数中得到未定义。

如何从reducer返回“返回的A”?

FooterFirst.js 是一个连接reducer的组件。

(这也有问题,但我猜它不会导致未定义的状态。也许......)

index.js 是 actioncreator。

FooterLink.js

    import {connect} from "react-redux"
    import {changeWindow} from "../actions"
    import {undefinedText} from "../actions"
    import FooterFirst from "../components/FooterFirst"
    const mapStateToProps =(state,ownProps)=>{
      return {
        text:state.text
      }
    }
    const mapDispatchToProps = (dispatch,ownProps)=>{
      if (ownProps.text === `undefined`){
        return{
          onClick:()=>{dispatch(undefinedText(ownProps.text))}
        }
      }
      return{
        onClick:()=>{dispatch(changeWindow(ownProps.text))}
        }
      }

    const FooterLink = connect(
      mapStateToProps,
      mapDispatchToProps
    )(FooterFirst)
    export default FooterLink

footerreducer.js

const footerreducer = (state,action) =>{
  if (typeof state=== 'undefined') {
    return Object.assign({},state,{
      text:"A"
    })
  }
  switch (action.type){
case `A`:
  return Object.assign({}, state, {
    text:`returned A`
  })
case `B`:
  return {
    text:`retruned B`
  }
case `C`:
  return {
    text:`returned C`
  }
default:
  return state
  }
}
export default footerreducer

FooterFirst.js

import React ,{PropTypes} from "react"
let x = 0
const FooterFirst = ({text,onClick})=>{
  if(!text){
    x = x + 1
    console.log(x)
    return <a text={text} onClick={e=>{e.preventDefault()
      onClick()
    }}>
    AAAA{text}
  </a>
  }

  return (
    <a text={text} onClick={e=>{e.preventDefault()
      onClick()
      }}>
      iefefer
  </a>
  )

}
FooterFirst.PropTypes ={
  text:PropTypes.string.isRequired,
  onClick:PropTypes.func.isRequired
}

export default FooterFirst

index.js

export const changeWindow  = (text_Now)=>{
  return { 
    type:`A`,
    text:text_Now
  }

}
export const undefinedText = (text_Now)=>{
  return {
    type:`Notext`,
    text:text_Now
  }
}

【问题讨论】:

标签: javascript reactjs redux


【解决方案1】:

您需要将 footerreducer 导入到 FooterLink。

【讨论】:

  • 终于成功了!我导入的不是footerrducer,而是rootreducer 到FooterLink。但它为什么起作用仍有待解决......
猜你喜欢
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多