gpt4 book ai didi

javascript - ReactJS:我有一个跳过第一个 Prop 方法的点击处理程序

转载 作者:行者123 更新时间:2023-11-30 11:52:17 24 4
gpt4 key购买 nike

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

var mode=[ 'recent', 'alltime'];

class Header extends React.Component {
constructor(){
super()
}

render(){
return <h2>Free Code Camp Leader board</h2>
}
}


class Leader extends React.Component {
constructor(props){
super(props)
this.state = {
users: [],
val: props.m
}
}

componentWillReceiveProps(props){
this.setState({val: props.m})
this.ajax();
}

componentWillMount() {
this.ajax();
}

ajax(){
this.serverRequest =
axios.get("https://fcctop100.herokuapp.com/api/fccusers/top/"+this.state.val)
.then((result) => {
console.log(result.data);
var leaders = result.data;
this.setState({
users: leaders
});
});
}

componentWillUnmount() {
this.serverRequest.abort();
}

render() {
console.log(this.state, this.props)
return (
<div className='container'>

<div className="tbl">
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Recent </th>
<th>Alltime</th>
</tr>
</thead>
<tbody>
{this.state.users.map(function(data, index){
return (<tr key={index}><td><img src={data.img} className="img img-thumbnail" width="50"/>{data.username}</td>
<td id='recent'>{data.recent}</td>
<td id='alltime'>{data.alltime}</td></tr>)
})}
</tbody>
</table>
</div>
</div>
)
}
}


class App extends React.Component{
constructor() {
super(),
this.state={val: mode[0]},
this.onClick= this.onClick.bind(this)
}

onClick() {
this.setState({val: this.state.val === mode[0]? mode[1] : mode[0]})
}

render() {
return (
<div>
<div className='header'>
<Header />
<button onClick={this.onClick} >{this.state.val==mode[0]? mode[1] : mode[0]}</button>
</div>
<div>
<Leader m={this.state.val} />
</div>
</div>
);
}
}

export default App;

由于某种原因,应用程序正确加载,但在第一次单击内部按钮时,它什么也没做;但是,除了与按钮上的文本不同步之外,它在随后的点击中工作得很好。 componentWillReceiveProps 方法的使用有问题吗?

最佳答案

首先,组件挂载时不会调用componentWillReceiveProps。检查doc .因此,您应该在 componentDidMount 中调用第一个 ajax 调用。

componentDidMount(){
this.setState({val: this.props.m},this.ajax);
}

其次,您应该知道 setState 方法是异步的。在您的 componentWillReceiveProps 中,您应该调用 this.ajax 方法作为 this.setState 方法的回调,以确保您的 this.state .val 在调用 ajax 时已经更新。

  componentWillReceiveProps(nextProps){
this.setState({val: nextProps.m},this.ajax);
}

还有一件事,确保 ajax 方法绑定(bind)到您的组件实例。

关于javascript - ReactJS:我有一个跳过第一个 Prop 方法的点击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39111515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com