【发布时间】:2021-06-18 02:53:06
【问题描述】:
添加项目屏幕
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 更新 Reducers 页面中的全局状态,最后在 Flatlist 中显示结果。
问题是当我运行代码时它会打印错误Cannot update a component from inside the function body of a different component。
【问题讨论】:
-
哪个状态更新导致该错误?
-
itemList,currentUser 一直运行良好
-
没有更新 itemList 的代码。在您的调度中,您应该将项目发送到 redux 商店。在派生状态下调度也可能导致无限循环。取而代之的是,您应该从添加项目组件更新 redux
-
代码中的另一个问题是您正在覆盖 onChangeText 中的整个状态。您应该在所有更改文本上做这样的事情:
this.setState({ ...this.state, name:name })
标签: javascript reactjs react-native redux react-redux