我刚起步,遇到两个问题:
console log
输入并单击一次提交按钮后显示映射的数据。但是单击两次按钮后,我得到了控制台记录的输入和映射的数据。这是我的应用程序组件中的代码:
import React, { Component, Fragment } from 'react';
import './App.css';
import Display from './/Display';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
passedValue: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
this.setState({ passedValue: this.state.value });
console.log(this.state.passedValue);
event.preventDefault();
}
render() {
return (
<div>
<form className="inputContainer" onSubmit={this.handleSubmit}>
<input type="text" name="company_name" onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
<Display listDataFromParent={this.state.passedValue} />
</div>
);
}
}
export default App;
这是我的显示组件:
import React, { Component } from 'react'
import "./Display.css";
export default class Display extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
data: []
};
}
componentWillReceiveProps() {
fetch("http://localhost:5000/company?company_name=" + this.props.listDataFromParent)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
data: result
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, data } = this.state;
// if (error) {
// return <div>Error: {error.message}</div>;
// } else if (!isLoaded) {
// return <div>Loading...</div>;
// } else {
return (
<div className="display">
<h1>Kreditnehmer</h1>
<ul>
{this.props.listDataFromParent}
{data.map(item => (
<li key={item.c.company_id}>
Relation type: {item.r.relation_group}
Last name: {item.p.last_name}
</li>
))}
</ul>
</div>
);
}
}
有人可以帮忙吗?
第一个问题的答案是:
应在setState
上使用回调函数,以便在状态真正更新后执行console.log
。
在您的情况下,您调用setState
并且setState
是async函数,这意味着console.log
不会等到状态真正更新后才使用。
您的代码应为:
handleSubmit(event) {
this.setState({ passedValue: this.state.value },
() => console.log(this.state.passedValue));
event.preventDefault();
}
1] React中的setState
是async
方法,这意味着需要一些时间来更新组件状态。您可以使用setState的回调函数获取控制台日志,例如
this.setstate({ value: e.target.value }, () => { console.log(this.state.value) });
2)在显示组件中,您使用componentWillReciveProps的生命周期,而在您使用this.props.listdatafromparent
的生命周期中,它指向先前的道具。建议不要考虑生命周期的this.props
参数,而不是使用props
,这意味着它应该像
componentWillReciveProps(props) {
// your code
Console.log(props.listdatafromparent);
}