reducer 更新了 apposArrayProp 但 Redux 没有更新我的视图

The reducer updates apposArrayProp but Redux doesn't update my view

我是 Redux 的新手,我想在调用 API 后更新数组 this.props.apposArrayProp,但我卡住了,操作和减速器被执行,但无论如何视图都不会改变。不知道connect方法中是否需要mapDispatchToProps。

我的actions.js文件

import fetch from 'isomorphic-fetch'

export const RECEIVE_APPOS   = 'RECEIVE_APPOS'

export function fetchAppos(appo_id) {
  console.log('in fetchAppos 148')
    return dispatch => {
      return fetch('/appointments/get_appos')
       .then(response => response.json())
       .then(json => dispatch(receiveAppos(json)))
 }
}

function receiveAppos(apposArrayProp) {
  console.log('receiveAppos Action>>>>>'+JSON.stringify(apposArrayProp))
  return {
    type:  RECEIVE_APPOS,
    apposArrayProp
  }
}

reducer 文件,appointments_Rdcer.js:

import { fetchAppos, RECEIVE_APPOS } from '../actions/actions'

const initialState = {
  apposArrayProp: []
}
const appointments_Rdcer = (state = initialState, action) => {
  switch (action.type) {
    case RECEIVE_APPOS:
      console.log('RECEIVE_APPOS REDUCER >>>'+
     JSON.stringify(action.apposArrayProp))
      return Object.assign({}, state, {
            apposArrayProp: action.apposArrayProp
        })

    default:
      return state
  }
}

export default appointments_Rdcer

最后是我的 Container.js 文件:

import { connect } from 'react-redux'
import React, { Component, PropTypes } from 'react'
import { ReactDom } from 'react-dom'
import * as ApposActionCreators from '../actions/actions'

class ApposComponent extends Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    console.log('In componentDidMount'+JSON.stringify(this.props))
    let action = ApposActionCreators.fetchAppos()
    this.props.dispatch(action)
  }
  render() {
    var tempo = ''
    var trNodes = this.props.apposArrayProp.map(function (appo) {
      tempo += appo.petname
      console.log('##  I want to see this #####' + tempo)
    })
    return (
      <div className="appoList">Display {tempo} </div>
    )
  }
}

ApposComponent.propTypes = {
  apposArrayProp: PropTypes.array.isRequired
}

ApposComponent.defaultProps = {
   apposArrayProp:  []
 }

const mapStateToProps = (state) => {
  return {
    apposArrayProp: state.apposArrayProp
  }
}

export default connect(mapStateToProps)(ApposComponent)

版本: "react": "^0.14.7", "react-redux": "^4.4.0", "redux": "^3.3.1",

我在日志中看到变化:

已解决

¡Dave Walsh!, ¡非常感谢!

我改变了我的减速器:

export default function rootReducer(state = {}, action) {
  return {
    appointments: appointments_Rdcer(state.appointments_Rdcer, action)
  }
}

至:

export default function rootReducer(state = {}, action) {
  return {
   appointments_Rdcer: appointments_Rdcer(state.appointments_Rdcer, action)
}

}

并听从了您的建议,现在一切正常。谢谢!

您的 mapStateToProps 函数应如下所示:

const mapStateToProps = (state) => {
  return {
    apposArrayProp: state.appointments_Rdcer.apposArrayProp
  };
};

这应该足以使其正常工作。

此外,我还鼓励您检查一下您的渲染逻辑。您正在使用 Array#map 就像它是 Array#forEach。你拥有的仍然可以使用,但有点难看。