[英]Passing data from child component to parent component error
單擊按鈕,我將數據從子組件傳遞到父組件,並將數據生成為圖形。 但是子組件的數據在狀態更新后立即顯示未定義,因此沒有數據傳遞給父組件。
這是我的父組件:
class ButtonAll extends Component{
constructor(props){
super(props);
this.state = {
childData: ''
}
}
getData = (data) => {
this.setState({
childData: data
})
}
render(){
return(
<div style={{ display: 'flex', flexDirection: 'row'}}>
<div>
<YearButton sendData={this.getData} />
</div>
</div>
)
}
export default ButtonAll;
這是我的子組件:
class YearButton extends Component{
constructor(){
super();
this.state = {
data1: [],
}
}
getData = async () => {
var res = await axios.get('http://132.148.144.133:5000/api/v1/resources/tweet/count/xxhkfh2873jiqlp');
var data1 = JSON.parse(res.data);
data1 = data1.map(el => [el[0]*1000, el[1]]);
console.log(data1, 'first data');
this.setState({
data1: data1
}, () => {
this.props.sendData(this.state.data1)
})
}
render(){
return(
<div>
<button className="year" onClick={this.getData}>year</button>
</div>
)
}
}
export default YearButton;
當我按下按鈕時,它將為this.props.sendData(this.state.data1)
這行undefined
。
對於其他組件,我也必須實現類似的功能,但是沒有任何東西可以傳遞給父級。 請幫忙。
在您的子組件中,在constructor
和super
傳遞props作為參數。
問題出在您的構造函數中。 如果使用構造函數,則必須提供道具作為構造函數和super的參數,如下所示。
class YearButton extends Component{
//the problem is here pass props as constructor param
constructor(props){
super(props);
this.state = {
data1: [],
}
}
// or remove constructor write state like below
state = {
data1 : [],
}
getData = async () => {
var res = await axios.get('http://132.148.144.133:5000/api/v1/resources/tweet/count/xxhkfh2873jiqlp');
var data1 = JSON.parse(res.data);
data1 = data1.map(el => [el[0]*1000, el[1]]);
console.log(data1, 'first data');
this.setState({
data1: data1
}, () => {
this.props.sendData(this.state.data1)
})
}
render(){
return(
<div>
<button className="year" onClick={this.getData}>year</button>
</div>
)
}
}
export default YearButton;
您沒有在構造函數中綁定getData()方法。
您的構造函數應如下所示
constructor(props) {
super(props);
this.getData = this.getData.bind(this);
this.state = {
data1: [],
}
}
您的子組件也是如此。 子組件中的函數應將此綁定到構造函數中。
希望這能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.