组件中的React-Redux派遣操作

时间:2019-03-24 22:52:43

标签: react-native react-redux connect

我本机反应很新,我遇到的问题是试图从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的函数。

更新:  目前,我的所有文件都是单独的(动作,reduce,常量,索引)。我的操作从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: ƒ}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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>
    );
  }
}