在刷新反应应用程序时,我需要从输入文本的componentWillReceiveProps值获取

时间:2018-03-22 17:20:10

标签: forms reactjs

我有以下问题,我真的需要帮助。

export class DeviceEdit extends React.PureComponent<Props> {

  constructor(props) {
    super(props);

    this.state = {
      value: ''
    };

    this.handleChange = this.handleChange.bind(this);
  }
  componentDidMount() {
    let data = this.props.devices.data.find(device => device.id === 
    `${deviceID}`) || {};

  this.setState({ value: data.name })

  }

  componentWillMount() {
     let data = this.props.devices.data.find(device => device.id === 
     `${deviceID}`) || {};

  this.setState({ value: data.name })
  }

 componentWillReceiveProps(newProps) {
  let data = newProps.devices.data.find(device => device.id === 
  `${deviceID}`) || {};

  this.setState({ value: data.name })
 }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

render() {
  const { error } = this.props;

  return (
   <FormLabel>Internal ID</FormLabel>
     <input type="text" defaultValue={this.state.value} onChange= . 
          {this.handleChange} />
     </Form.Label>)
   }
  }

所以我想要的是当我刷新页面时,我想在输入中获取this.state.value ..在这种情况下我无法做到这一点。所以我想知道我在这里做错了什么。如果我在输入上将其设置为值,我确实得到了我想要的东西,但之后我发出了类似的警告:

A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component

我该怎么办?

2 个答案:

答案 0 :(得分:0)

实际上,您应该在那里处理更改,并且只能在输入字段上使用value而不是defaultValue

例如:

export class AdminDeviceEdit extends React.PureComponent<Props> {

  constructor(props) {
    super(props);

    this.state = {
      value: '',

      // if it comes from props by default 
      // you can use, if not just leave as it is
      value: props.value
    };
  }

   handleChange = e => {
      this.setState({value: e.target.value});
   }

   render() {
      const { error } = this.props;

      return (
         <form>
           <FormLabel>Internal ID</FormLabel>
           <input type="text" value={this.state.value} onChange={this.handleChange} />
         </form>
      )
   }
}

希望它会有所帮助。

答案 1 :(得分:0)

因此,根据我的理解,您希望进行受控输入,但使用props.value作为默认值。如果你这样做了:

export class AdminDeviceEdit extends React.PureComponent<Props> {

  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  componentWillReceiveProps(newProps) {
    if(this.props.value !== newProps.value) {
      this.setState({ value: newProps.value }) // reset input value
    }
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    const { error } = this.props;

    return (
     <FormLabel>Internal ID</FormLabel>
       <input type="text" value={this.state.value} onChange={this.handleChange} />
     </Form.Label>)
   }
}

当然要摆脱componentWillMountcomponentDidMount。你在这里不需要它们。