javascript - componentDidUpdate 不使用 Redux 更新状态
问题描述
这个应用程序的目标是让我们Flatlist
在列表项目屏幕的礼物中添加一个项目,使用React-Redux
和React Navigation
。基本上,我在 Create Item 屏幕中输入名称和类别,并使用 React Navigation 以数组的形式将其发送到 List Item 屏幕,一旦我进入 List Item 屏幕,我就使用它componentDidMount
来调度操作并更新状态类组件,问题是什么都没有显示,即使使用console.log
它也只会让我返回 Redux Reducers 屏幕中存在的空数组。
创建项目屏幕
export class item extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
category: '',
};
}
submitItem = (name, category) => {
this.props.navigation.navigate("ListItem", {
itemList: {
name: name,
category: category,
}});
};
render() {
const { name, category } = this.state;
return (
<Container>
<Header>
<Left>
<Button onPress={() =>
this.submitItem(
this.state.name,
this.state.category,
)
}>
<Text>Sumbit</Text>
</Button>
项目列表屏幕
class ListItem extends Component {
constructor(props) {
super(props);
this.state = {
itemList:[],
};
}
componentDidMount (props, state) {
if (this.props.route.params?.itemList) {
() => this.props.dispatch({type:'ADD_ITEM'});
}
return null;
}
REDUX 减速机
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{
itemList: state.itemList,
}
default:
return state
}
};
解决方案
我认为当您调度一个动作时,您并没有将 action.payload 添加到 state.itemList。我的意思是
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{
...state,
itemList: addItemToList(state.itemList,action.payload), //a util function to add items to the list.
// And action.payload is the value ,which passed when you are dispatching the action 'ADD_ITEM'
}
default:
return state
}
};
当您发送操作时,它应该是
componentDidMount (props, state) {
if (this.props.route.params?.itemList) {
() => this.props.dispatch({type:'ADD_ITEM',payload:this.props.route.params.itemList});
// passing the itemList to as the payload of the action.
}
return null;
}
我想这个修改应该足够了。更多关于 React-Redux 的信息在这里
推荐阅读
- r - R中数据帧的图例
- css - 如何显示图标可以用光标悬停
- mocha.js - 为什么即使在 .nycrc 中添加了包含后,nyc 也找不到类?
- node.js - 使用带有 xmlbuilder 的 createWriteStream 会消耗大量内存
- javascript - 使用 express 验证器重复消息
- macos - AppleScript 错误:“邮件出错:无法将文本项分隔符设置为 {"+"、"@"}。"
- c# - 未显示分组集合视图列表,可能存在绑定错误
- reactjs - 部署 Django 并将应用程序响应 Azure 应用程序服务后的后续步骤
- asp.net - 如何使用 XAMPP 在服务器上运行 ASP.NET 网站?
- unix - crontab 调度问题