我可以訪問獲取的this.state之外,但在嘗試訪問狀態裏面取的時候,我得到這個錯誤:ReactJS不能與狀態,錯誤獲取:「無法讀取空的特性‘國家’」
Uncaught TypeError: Cannot read property 'state' of null
我翻翻了StackOverflow上的其他帖子,但沒有找到一個可以在fetch調用中使用狀態屬性的工作解決方案。請幫忙。
class SignIn extends React.Component {
constructor(props){
super(props);
this.state = {
email: '',
password: ''
}
this.handleValueChange = this.handleValueChange.bind(this);
}
handleValueChange(event) {
const property = event.target.name;
this.setState({[property]: event.target.value});
}
handleLogin(event){
event.preventDefault();
fetch("http://localhost:3001/login.json", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email, //this is where the error occurs
password: '123456'
})
})
.then(function(res){return res.json();})
.then(function(data){console.log(data)});
}
render() {
return(
<header>
<NavigationBar />
<div className="form-box">
<form onSubmit={this.handleLogin}>
<h2>Login</h2>
<br />
<div className="row">
<div>
<label>Email</label>
<input type="text" name="email" ref='emailInputField'
onChange={(event) => this.handleValueChange(event)}
required
/>
</div>
</div>
<br />
<div className="row">
<div>
<label>Password</label>
<input type="text" name="password"
onChange={(event) => this.handleValueChange(event)}
required
/>
</div>
</div>
<br />
<div className="btn-submit">
<input type="submit" value="Let's go!" />
</div>
</form>
<button onClick={() => console.log("this.state", this.state)} >Show state</button>
</div>
</header>
)
}
}
注意:一些代碼沒有顯示簡潔
忘了綁定'handleLogin'方法,把這一行放在構造函數中:'this.handleLogin = this.handleLogin.bind(this)' –
你不能在那裏訪問狀態。將該值作爲參數,道具等傳遞。 – jmargolisvt