【问题标题】:React Redux - Uncaught TypeError: Cannot read property 'setState' of undefinedReact Redux - 未捕获的类型错误:无法读取未定义的属性“setState”
【发布时间】:2017-06-11 09:16:57
【问题描述】:

新手。

我一直在寻找答案 herehere

我也在使用 Redux。根据良好做法,我有一个容器“AddressContainer”及其组件“Address”。

AddressContainer如下——

import React, { Component, PropTypes } from 'react'
        import { connect } from 'react-redux'
        import { Field, change } from 'redux-form'
        import { Col, Panel, Row } from 'react-bootstrap'
        import Select from 'react-select'

        import Address from './address'

        import { ensureStateData, getSuburbs } from './actions'

        import { CLIENT_FORM_NAME } from '../clients/client/client'

        export class AddressContainer extends Component {
          static contextTypes = {
            _reduxForm: PropTypes.object.isRequired,
          }

          constructor(props, context) {
            super(props, context)

            this.state = {
              selectedSuburb: null,
            }
          }

          componentDidMount() {
            this.props.ensureStateData()
          }

          // Manage asyncSelect for new data request - for suburbs.
          handleSuburbSearch = (query) => {
            const { addressData } = this.props
            const companyStateId = addressData.companyStateId

            if (!query || query.trim().length < 2) {

              return Promise.resolve({ options: [] })
            }
            const queryString = {
              query: query,
              companyStateId: companyStateId,
            }
            return getSuburbs(queryString)
              .then(data => {
                return { options: data }
              })
          }


          render() {
            const {
              initialValues,
              addressData,
              updatePostcodeValue,
            } = this.props


            //const { value } = this.state
            const sectionPrefix = this.context._reduxForm.sectionPrefix


            if (addressData.isLoading || !addressData.states.length) {
              return (
                <p>Loading</p>
              )
            }
            if (addressData.error) {
              return (
                <p>Error loading data</p>
              )
            }


            const companyStateId = addressData.companyStateId
            //  initialValues = {
            //    ...initialValues.Address=null,
            //    state: addressData.states.find(option => option.stateId === companyStateId),
            //  }


            return (
              <Address 
                initialValues={initialValues}
                addressData={addressData}
                handleSuburbSearch={this.handleSuburbSearch}
              />
            )
          }
        }
        const mapStateToProps = (state) => ({
          initialValues: state.address,
          companyStateId: state.companyStateId,
          addressData: state.addressData,
        })

        const mapDispatchToProps = (dispatch) => ({
          ensureStateData: () => dispatch(ensureStateData()),
          getSuburbs: (values) => dispatch(getSuburbs(values)),
          updatePostcodeValue: (postcode, sectionPrefix) => dispatch(change(CLIENT_FORM_NAME, `${sectionPrefix ? (sectionPrefix + '.') : ''}postcode`, postcode))
        })

        export default connect(mapStateToProps, mapDispatchToProps)(AddressContainer)

Address组件如下——

import React, { Component, PropTypes } from 'react'
      import { connect } from 'react-redux'
      import { Field, reduxForm, change } from 'redux-form'
      import { Col, Panel, Row } from 'react-bootstrap'
      import Select from 'react-select'
      import FormField from '../formComponents/formField'
      import TextField from '../formComponents/textField'
      import StaticText from '../formComponents/staticText'

      export const ADDRESS_FORM_NAME = "Address"

      export const Address = (props) => {
        const { addressData, handleSuburbSearch } = props
        const { reset } = props

        return (
          <Panel header={<h3>Client - Address Details</h3>}>
            <Row>

              <Field component={TextField}
                name="address1"
                id="address1"
                type="text"
                label="Address Line 1"
                placeholder="Enter street 1st line..."
                fieldCols={6}
                labelCols={3}
                controlCols={9}
              />
              <Field component={TextField}
                name="address2"
                id="address2"
                type="text"
                label="Address Line 2"
                placeholder="Enter street 2nd line..."
                fieldCols={6}
                labelCols={3}
                controlCols={9}
              />
            </Row>
            <Row>
              <Field
                component={props => {
                  const { input, id, placeholder, type } = props
                  const { fieldCols, labelCols, controlCols, label, inputClass } = props
                  // just the props we want the inner Select textbox to have
                  const { name, onChange } = input
                  const onStateChange = (state) => {
                    console.log('onStateChange', state)
                    onChange(state)
                  }

                  return (
                    <FormField
                      id={id}
                      label={label}
                      fieldCols={fieldCols}
                      labelCols={labelCols}
                      controlCols={controlCols}
                      inputClass={inputClass}
                    >
                      <Select
                        name={name}
                        onChange={onStateChange}
                        placeholder="Select state"
                        valueKey="id"
                        options={addressData.states}
                        labelKey="stateLabel"
                        optionRenderer={option => `${option.stateShortName} (${option.stateName})`}
                        value={input.value}
                        selectValue={Array.isArray(input.value) ? input.value : undefined}
                      />

                    </FormField>
                  )
                }}
                name="state"
                id="state"
                label="State."
                fieldCols={6}
                labelCols={3}
                controlCols={6}
              />

            </Row>
            <Row>
              <Field
                component={props => {
                  const { input, id, placeholder, type } = props
                  const { fieldCols, labelCols, controlCols, label, inputClass } = props
                  const { name, value, onChange, onBlur, onFocus } = input
                  const inputProps = {
                    name,
                    value,
                    onChange,
                    onBlur,
                    onFocus,
                  }
                  const onSuburbChange = (value) => {
                    console.log('onSuburbChange: ', value)
                    this.setState({ selectedSuburb: value }, () => {
                      input.onChange(value)
                      updatePostcodeValue(value ? value.postcode : null, sectionPrefix)
                    })
                  }

                  return (
                    <FormField
                      id={id}
                      label={label}
                      fieldCols={fieldCols}
                      labelCols={labelCols}
                      controlCols={controlCols}
                      inputClass={inputClass}
                    >
                      <Select.Async
                        {...inputProps}
                        onChange={onSuburbChange}
                        valueKey="id"
                        labelKey="suburbName"
                        loadOptions={handleSuburbSearch}
                        backspaceRemoves={true}
                      />
                    </FormField>
                  )
                }}
                name="suburb"
                id="AddressLocation"
                label="Suburb."
                fieldCols={6}
                labelCols={3}
                controlCols={9}
              />

            </Row>
            <Row>
              <Field component={StaticText}
                name="postcode"
                id="postcode"
                label="Postcode."
                fieldCols={6}
                labelCols={3}
                controlCols={9}
              />

            </Row>
          </Panel>
        )

      }

      Address.propTypes = {
        handleSuburbSearch: PropTypes.func.isRequired,
      }

      const AddressForm = reduxForm({
        form: ADDRESS_FORM_NAME,
      })(Address)

      export default AddressForm

问题在于下面地址组件中的以下函数以及它说未定义的 setState -

         const onSuburbChange = (value) => {
          console.log('onSuburbChange: ', value)
          this.setState({ selectedSuburb: value }, () => {
            input.onChange(value)
            updatePostcodeValue(value ? value.postcode : null, sectionPrefix)
          })
        }

您会注意到“值”有一个 console.log。这会产生结果:

onSuburbChange: Object {id: 6810, suburbName: "Eaglehawk", postcode: "3556", state: "VIC"}

我使用 React-Select 作为异步下拉菜单。这一切都有效。如果我选择一个选项,我会得到下拉选项,但选择一个,它会给我错误。

我在这里为 selectSuburb 选项使用反应状态,因为我不需要用它来更新 redux - 只是反应状态。

看起来没问题,但我仍然收到错误消息。为什么会出现此错误,如何解决?

【问题讨论】:

  • 您正在为无状态功能组件设置状态,这就是它给您此错误的原因
  • 你能详细说明一下吗?我不确定如何纠正这个问题。我以为我在容器中设置了状态,特别是在 onSuburbChange 的构造函数中。我该如何解决这个问题..

标签: reactjs react-redux


【解决方案1】:

这个特定的错误是由于&lt;Address /&gt;组件是一个无状态的功能组件,不能有this.state对象或setState函数。但是,更一般地说,您似乎期望 &lt;AddressContainer /&gt; 组件中的状态和函数可用于子 &lt;Address /&gt; 组件,但这不可能发生。在这种情况下,您希望通过在子级上调用 setState 来修改父级的状态。

子 React 组件(在本例中为 &lt;Address /&gt;)将仅具有来自其父组件的状态/函数/属性,作为道具显式传递给该组件。如果您想更改组件的本地状态它必须发生在具有本地状态的组件上。如果您想让子组件在父组件上触发某种类型的函数调用,则必须将该函数作为道具传递给子组件,并且子组件可以调用它。

如果我正确理解您的代码,您希望在更改 Suburbs FormField 时按此顺序发生 3 件事。

  1. &lt;AddressContainer /&gt; 上的 selectedSuburb 状态已更新。
  2. &lt;Address /&gt; 中 Redux-Form &lt;Field /&gt;onChange 被触发。
  3. updatePostCode 操作被触发。

如果正确,那么您需要将您的 onSuburbChange 移动到 &lt;AddressContainer /&gt; 并将其作为道具传递给 &lt;Address /&gt;。但是,您不能在 &lt;AddressContainer /&gt; 中调用 Redux-Form &lt;Field /&gt;onChange。因此,您可以使该函数期望接收一个回调函数,该回调函数将在状态更新后触发。然后您可以在子组件中定义回调,但在父组件中定义状态更改函数。只要您在父节点上传递所需的道具,例如updatePostCodesectionPrefix,您就会很成功。这是它的样子:

地址容器

export class AddressContainer extends Component {
  /* Everything else in this component */

  onSuburbChange = (value, callback) => {
    this.setState({ selectedSuburb: value }, callback);
  }

  render() {
    /* Other stuff inside render */

    return (
      <Address 
        initialValues={initialValues}
        addressData={addressData}
        handleSuburbSearch={this.handleSuburbSearch}
        onSuburbChange={this.onSuburbChange}
        updatePostcodeValue={this.props.updatePostcodeValue}
        sectionPrefix={sectionPrefix}
      />
    );
  }
}

地址

export const Address = (addressProps) => {
  return (
    /* All other JSX */

    <Field
      component={props => {
        const { input } = props;

        const handleSuburbChange = (value) => {
          addressProps.onSuburbChange(value, () => {
            input.onChange(value);
            addressProps.updatePostcodeValue(value ? value.postcode : null, addressProps.sectionPrefix)
          });
        }

        return (
          <Select.Async
            onChange={handleSuburbChange}
          />
        )
      }}
  );
}

如您所见,&lt;Address /&gt; 组件中不同的props 变量之间将存在命名冲突,因此我将主要属性称为addressProps 以避免这种情况。

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 2018-07-04
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多