2016-11-06 99 views
1

我一直獲得this.setState警告:反應上安裝或安裝

警告:的setState(...):只能更新一安裝或安裝 組件。這通常意味着您在未安裝的組件上調用了setState()。這是一個沒有操作。請檢查SearchInput 組件的代碼。

我曾嘗試以下這些:
https://facebook.github.io/react/docs/two-way-binding-helpers.html#linkedstatemixin-before-and-after

https://stackoverflow.com/questions/21029999/react-js-identifying-different-inputs-with-one-onchange-handler

https://stackoverflow.com/questions/28773839/react-form-onchange-setstate-one-step-behind

問題是簡單的:當用戶鍵入到輸入字段中捕獲經由onChange屬性輸入和setState

import React, { Component } from 'react'; 

class SearchInput extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     inputValue: '' 
    }; 
    this.onChange = this.onChange.bind(this); 
    } 

    render() { 
    return (
     <input 
     type="text" 
     value={this.state.inputValue} 
     onChange={this.onChange} /> 
    ); 
    } 

    onChange(e) { 
    console.log('yo'); 
    this.setState({ inputValue: e.target.value }); 
    } 
} 

export default SearchInput; 

如何安裝我的組件,以便警告消失,並且我可以更新用戶輸入狀態?

UPDATE
最近,我改變了我的.babelrc文件到這一點:

{ 
    "presets": ["latest-minimal", "stage-1", "react"], 
    "plugins": ["react-hot-loader/babel"] 
} 

以下這一點:https://github.com/gabmontes/babel-preset-latest-minimal

但只要我恢復到了我面前:

{ 
    "presets": ["es2015", "stage-1", "react"], 
    "plugins": ["react-hot-loader/babel"] 
} 

警告消失了。

latest-minimal中的某些東西沒有jiving。

+0

在什麼情況下您會收到警告? – zerkms

+0

'state = { inputValue:'「 }' 嘗試在構造函數上方分配狀態,而不是在 –

+0

100%確定該錯誤與上面的代碼無關。 – FurkanO

回答

-1

使用defaultValue代替值。

render() { 
return (
    <input 
    type="text" 
    defaultValue ={this.state.inputValue} 
    onChange={this.onChange} /> 
); 
} 

結帳此不受控制組件概念:

https://facebook.github.io/react/docs/forms.html#uncontrolled-components

基本上輸入保持其自身的狀態時設置值使用表達會觸發在輸入組件的狀態變化(未安裝部件),而呈現SearchInput部件。