组件中的 React-Redux 调度操作

React-Redux Dispatch Action in Component

我是 React Native 的新手,我遇到的问题是尝试从 componentdidmount 中的操作获取数据,但是当我设置道具时,数据为空。如果我在 render 方法中访问它们,就会设置这些道具。有人可以看看代码并告诉我我做错了什么吗?

下面是我进行操作的地方

export const Accountability = connect(

// inject states
(state: States) => ({

    // props.loading -> modules.app.loading
    loading: state.app.loading,
    doctorName: state.doctor.doctorName
}),

// inject actions
dispatch => ({
     doDoctors: () =>
        dispatch(actions.doctor.getDoctors())
 })
 )(AccountabilityView)

这就是我调用它的地方。

render() {
 const {loading, doDoctors, doctorName } = this.props

 // Getting the data here. 
 doDoctors()
 }

我注意到的一件事是我在控制台中收到警告

ExceptionsManager.js:82 警告:无法在现有状态转换期间更新(例如在 render 内)。渲染方法应该是 props 和 state 的纯函数。

更新: 我目前将所有文件分开(操作、减速器、常量、索引)。我的操作从 API 调用中获取数据。下面是我的减速器:

import { handleActions } from 'redux-actions'
import { LOAD_DOCTORS } from './constants'

export type DoctorState = {
doctorName: string
}

const initialState: DoctorState = {
doctorName: '',
}

export default handleActions(
{
    [LOAD_DOCTORS]: (state: DoctorState = initialState, action): DoctorState 
 => {
        const p = action.payload
        return {
            doctorName: p.doctorName,
        }
      },
   },
   initialState
)

更新:2 这是代码在控制台中显示的内容,请注意 doDoctors,其中 returns 数组在第一次调用时为空。在 ComponentDidMount 中调用时,它只显示第一个而不显示第二个。

ComponentDidMount

{screenProps: undefined, navigation: {…}, loading: true, doctorName: "", 
doDoctors: ƒ}

渲染

{screenProps: undefined, navigation: {…}, loading: true, doctorName: "", 
doDoctors: ƒ}
{screenProps: undefined, navigation: {…}, loading: true, 
doctorName: Array(10), doDoctors: ƒ}

如有任何帮助,我们将不胜感激。

您可以调用 action 的可能事件是 => componentDidMountcomponentWillReceiveProps ... render 方法仅用于返回一些 jsx 基于你组件的更新 props:

class YourComponent extends React.Component {
  componentDidMount() {
    // Here's where you call your action,
    // first time your component is loaded: <<<===
    this.props.doDoctors();
  }

  componentWillReceiveProps(nextProps) {
    // Here's where you could call your action,
    // if the component is already mounted: <<<===
    this.props.doDoctors();
  }

  render() {
    const {loading, doctorName } = this.props;

    return (
      <View>
        ...
      </View>
    );
  }
}