【发布时间】:2016-12-30 16:33:36
【问题描述】:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
var mode=['recent', 'alltime'];
var Button = React.createClass({
render(){
return <input type={this.props.type} onClick= {this.props.onClick} text={this.props.val}/>;
}
});
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,
}
}
componentDidMount() {
var th =this;
this.serverRequest = axios.get("https://fcctop100.herokuapp.com/api/fccusers/top/"+this.state.val).then(function(result){
console.log(result.data);
var leaders = result.data;
this.setState({
users: leaders
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render(){
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.update= this.update.bind(this),
this.unmount=this.unmount.bind(this)
}
unmount(){
ReactDOM.unmountComponentAtNode(document.getElementById('board'))
}
update(){
this.unmount();
this.setState({val: this.state.val ===mode[0]? mode[1] : mode[0]});
}
render(){
return (
<div>
<div className='header'>
<Header />
<button onClick={this.update} >{this.state.val==mode[0]? mode[1] : mode[0]}</button>
</div>
<div id="board">
{this.state.val === mode[0]? <Leader m= {this.state.val} /> : this.state.val ===
mode[1] ? <Leader m= {this.state.val} /> : null}
</div>
</div>
);
}
}
export default App;
有问题的部分是在类 App extends React.Component 下。我正在尝试使用更新方法中的状态更改重新渲染领导者组件。它会更改状态,但不会更改传递给 Leader 以重新渲染的属性。
【问题讨论】:
-
打电话
unmount()的目的是什么。如果你只是评论那条线,你有同样的行为吗? -
我认为问题是
componentDidMount仅在初始渲染发生后立即在客户端(而不是服务器)上调用一次。如果您将this.state.val移动到领导者渲染,它应该会更新。 -
好的,谢谢,是的,unmount() 函数只是一个尝试在 val 属性上的 steState 之前卸载 Leader 的实验。目前它是一个无用的功能,很可能需要删除。
-
小提示:如果你将
get调用中的匿名函数回调改为(result) => {},那么你就不需要在最后调用bind(this),因为=>("箭头") 函数在词法上传递this.
标签: javascript reactjs