当我点击App组件中的Next按钮,传递其他网站时,我试图更改我执行获取请求的网站
<FilterableProductTable getSite={ this.state.active ? '/get_platfo
rms' : '/get_features' } />
但它不起作用,它只显示旧信息。我认为是一些异步问题
export class FilterableProductTable extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
fetch() {
axios.get(this.props.getSite)
.then(res => {
this.setState({
posts: res.data.functionality
});
});
}
componentDidMount() {
this.fetch();
setTimeout(function(){this.fetch();} , 5000);
}
render() {
return (
<div>
<ProductTable products={this.state.posts} />
</div>
);
}
}
export class App extends React.Component {
constructor(props){
super(props);
this.state= {active: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
active: !prevState.active
}));
}
render() {
return (
<div>
<FilterableProductTable getSite={ this.state.active ? '/get_platforms' : '/get_features' } />
<a className={ this.state.active ? 'button' : 'hidden' } onClick={this.handleClick}><span>Next</span></a>
</div>
);
}
}
答案 0 :(得分:0)
试试这段代码:
export class FilterableProductTable extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
fetch() {
axios.get(this.props.getSite)
.then(res => {
this.setState({
posts: res.data.functionality
});
});
}
componentDidUpdate(){
this.fetch();
}
componentDidMount() {
this.fetch();
setTimeout(function(){this.fetch();} , 5000);
}
render() {
return (
<div>
<ProductTable products={this.state.posts} />
</div>
);
}
}
export class App extends React.Component {
constructor(props){
super(props);
this.state= {active: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
let newState = !this.state.active;
this.setState({
active: newState
});
}
render() {
return (
<div>
<FilterableProductTable getSite={ this.state.active ? '/get_platforms' : '/get_features' } />
<a className={ this.state.active ? 'button' : 'hidden' } onClick={this.handleClick}><span>Next</span></a>
</div>
);
}
}
您的版本的更改:捕获componentDidUpdate事件(如果调用组件更新了fetch)并更改了handleClick方法。如果这可以解决您的问题,请告诉我。