Reactjs 更新状态和分派操作
我正在从API调用获取数据。因此,在Reactjs 更新状态和分派操作,reactjs,react-native,react-redux,Reactjs,React Native,React Redux,我正在从API调用获取数据。因此,在componentWillMount上,我正在进行API调用,它是mappedDispatchToProps:fetchCats class Cats extends Component { constructor(props){ super(); this.state = { toPass: 0 } } componentWillMount() { this.props.fetchCats(t
componentWillMount
上,我正在进行API调用,它是mappedDispatchToProps
:fetchCats
class Cats extends Component {
constructor(props){
super();
this.state = {
toPass: 0
}
}
componentWillMount() {
this.props.fetchCats(this.state.toPass);
};
getCats(){ // <= Is this the proper way to update the state and call the api?
this.setState({
toPass: this.state.toPass+2 //<= increment by 2
});
this.props.fetchCats(this.state.toPass);
}
renData() {
//map the array this.props.categories and return data
}
render(){
const { categories } = this.props.categories
console.log("CATEGORIES: ", categories);
return (
<View>
<View>
<Button
name="PressMe"
onPress={() => this.getCats()}>
</Button>
</View>
<View>
{this.reData()}
</View>
</View>
)
}
}
类扩展组件{
建造师(道具){
超级();
此.state={
toPass:0
}
}
组件willmount(){
this.props.fetchCats(this.state.toPass);
};
getCats(){/尝试以下操作:
getCats = () => {
this.setState({
toPass: this.state.toPass+2
}, () => {this.props.fetchCats(this.state.toPass)});
}
并使用onPress={this.getCats}
更改onPress行,尝试以下操作:
getCats = () => {
this.setState({
toPass: this.state.toPass+2
}, () => {this.props.fetchCats(this.state.toPass)});
}
并使用onPress={this.getCats}
更改onPress行,这可能是我假设的this.props.fetchCats(this.state.toPass)看到的类似代码片段的初始猜测的重复;
正在调用您的redux操作,该操作对类别
有作用。如果是这样,则此状态。在调用fetchCats
时,不保证更新toPass
。因此,第一次会得到一个重复的条目0。此后每隔一次,您只需从上一个异步操作。请参阅链接副本以了解原因和如何修复此问题。还有一件事,您甚至可以通过添加{this.state.toPass}来验证这可能是问题所在
在渲染中,您将看到它最终被更新为最新的值,该值可能与类别中的最后一个值不匹配。确切地说,我已经在执行{this.state.toPass}
并且该值仅显示了在上一次的onPress
中它应该是什么。非常感谢您的时间和解释。可能只是看到了与我假设的this.props.fetchCats(this.state.toPass)类似的代码片段的初始猜测的重复;
正在调用您的redux操作,该操作对类别
有作用。如果是这样,则此状态。在调用fetchCats
时,不保证更新toPass
。因此,第一次会得到一个重复的条目0。此后每隔一次,您只需从上一个异步操作。请参阅链接副本以了解原因和如何修复此问题。还有一件事,您甚至可以通过添加{this.state.toPass}来验证这可能是问题所在
在渲染中,您将看到它最终被更新为最新的值,该值可能与类别中的最后一个值不匹配。确切地说,我已经在执行{this.state.toPass}
而该值只显示了在上一次的onPress
中它应该是什么。非常感谢您的时间和解释。非常有用!非常感谢。那么这里有什么问题?为什么我调用的方式不起作用?setState
是一个异步调用。您没有等待对的回调代码>当您在赋值时使用方括号时,实际上是在调用函数。由于setState是异步的,您需要使用callback。工作起来很有魅力!非常感谢。那么这里有什么问题?为什么我调用的方式不起作用?setState
是异步调用。您没有等待对fetchCats在赋值时使用方括号时,实际上是在调用函数。由于setState是异步的,所以需要使用回调函数。