[英]React Native Redux doesn't update array
添加项目屏幕
export class additem extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
price: "",
category: "",
};
}
submitItem = (name, price, category) => {
this.props.navigation.navigate("ItemList", {
item: {
name: name,
price: price,
category: category,
}});
};
render(){
return(
<View>
<TextInput onChangeText={(name) => this.setState({ name })}/>
<TextInput onChangeText={(price) => this.setState({ price })}/>
<TextInput onChangeText={(category) => this.setState({ category })}/>
<Button onPress={() => this.submitItem(
this.state.name,
this.state.price,
this.state.category,
)}/>
</View>
)}
列表项目屏幕
import {connect} from 'react-redux';
class ItemList extends Component {
constructor(props) {
super(props);
this.state = {
itemList:[],
};
}
static getDerivedStateFromProps(props, state) {
if (props.route.params?.item) {
props.dispatch({type:'ADD_ITEM'});
}
return null;
}
render() {
return (
<FlatList
data={this.props.itemList}
contentContainerStyle={{ flexGrow: 1 , flexGrow: hp('20%')}}
renderItem={({ item }) => (
<View>
///output from flatlist
</View>
)}/>
);
}
}
function mapStateToProps(store){
return{
itemList: store.userState.itemList,
};
}
export default connect(mapStateToProps)(ItemList);
REDUX 屏幕减速器
import { USER_STATE_CHANGE } from "../constants";
const initialState = {
currentUser: null,
itemList: [],
};
export const user = (state = initialState, action) => {
switch (action.type){
case USER_STATE_CHANGE:
return {
...state,
currentUser: action.currentUser,
};
case 'ADD_ITEM':
return{
item: state.itemList,
}
default:
return state
}
};
您好,我正在学习React-Redux
,但遇到了一个问题。 该应用程序的目标是从添加项目屏幕添加一个杂货项目,一旦我使用Button
提交它,它就会将我发送到项目列表页面。
到达那里后,我使用static getDerivedStateFromProps
来检查数组是否已发送,并使用 Redux 更新Flatlist
页面中的全局状态,最后将结果显示在Flatlist
。
问题是,当我运行代码时,它会打印错误Cannot update a component from inside the function body of a different component
。
您应该从 addItem 文件调度一个动作。
您可以让两个在商店中添加一个变量,例如“加载”,并在分派操作“addItem”之前通过调用另一个操作将该变量设置为 true,并在成功添加项目后使加载变量为 false
并在 addItem 组件中将其设置为 true 后侦听加载为 false,然后导航到下一个屏幕
在您的代码中,问题是您在 getDerivedState 方法中调度一个动作(这似乎是问题所在)
或者您可以在小吃展上制作 POC,以便我们更好地了解谢谢:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.