首页 > 解决方案 > componentDidUpdate 不使用 Redux 更新状态

问题描述

这个应用程序的目标是让我们Flatlist在列表项目屏幕的礼物中添加一个项目,使用React-ReduxReact 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
  }
  
};

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


我认为当您调度一个动作时,您并没有将 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 的信息在这里


推荐阅读