我正在尝试通过单击一些调用方法来增加状态值的文本来进行分页。然后状态值被传递给axios调用,然后该调用将调用下一页。然而,我注意到当状态从render函数中获得console.log中的增量时,不会再次使用新的状态值调用axios调用。任何人都知道如何解决这个问题?
constructor(props) {
super(props);
this.state = {
people: [],
planets: [],
page: 1
};
this.pageIncrementer = this.pageIncrementer.bind(this);
}
componentWillMount() {
let page = this.state.page;
axios({
method: 'GET',
url: `http://localhost:3008/people?_page=${page}&_limit=10`
}).then((response) => {
this.setState({
people: response
});
}).catch((error) => {
console.log('There is an error in the Card axios call for people: ', error);
})
axios({
method: 'GET',
url: `http://localhost:3008/planets?_page=${page}&_limit=10`
}).then((response) => {
this.setState({
planets: response
});
}).catch((error) => {
console.log('There is an error in the Card axios call for planets: ', error);
})
}
pageIncrementer() {
this.setState({
page: this.state.page + 1
});
}
答案 0 :(得分:0)
componentWillMount
只调用一次,您需要componentDidUpdate
https://facebook.github.io/react/docs/react-component.html#componentdidupdate
let getData = () => Math.random();
class Example extends React.Component{
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this)
this.state = {
name: ''
};
}
componentWillMount(){
console.log('componentWillMount')
}
componentDidUpdate(){
console.log('componentDidUpdate')
}
handleChange(e) {
this.setState({
name: this.props.getData()
});
}
render() {
return <div className="widget">
{this.state.name}
<button onClick={this.handleChange}>Inc</button>
</div>;
}
}
React.render(<Example getData={getData}/>, document.getElementById('container'));
编辑(替代方式):
let getData = () => Math.random();
class Example extends React.Component{
constructor(props) {
super(props);
this.makeRequest = this.makeRequest.bind(this)
this.state = {
page:1,
name:''
};
}
makeRequest(next){
fetch('https://jsonplaceholder.typicode.com/posts/'+this.state.page)
.then(
result => {
console.log('do')
return result.json()}
)
.then(
(resp) => this.setState({
name:resp, page:this.state.page+1})
)
}
render() {
return <div className="widget">
{this.state.name}
<button onClick={this.makeRequest}>Request</button>
</div>;
}
}
React.render(<Example getData={getData}/>, document.getElementById('container'));