组件中的React-Redux调度操作

问题描述 投票:0回答:1

我对原生的反应相当新,我遇到的问题是尝试从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中)无法更新。渲染方法应该是道具和状态的纯函数。

更新:我目前将所有文件分开(动作,减速器,常量,索引)。我的操作从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为空。在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: ƒ}

任何帮助,将不胜感激。

react-native react-redux connect
1个回答
0
投票

您可以调用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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.