首页 > 解决方案 > React Redux 不更新 initialState

问题描述

我一直在尝试在我的 React Native 应用程序中应用 Redux,但 initialState 只是没有更新,当我运行代码时它返回mapStateToProps() in Connect(List) must return a plain object. Instead received undefined.undefined is not an object (evaluating '_this3.state'). 我还在学习,这是我到目前为止的地方。目标是让用户在数组中键入namelastname插入,list并用于dispatch更新listreducer 中的 initialState 提前谢谢您的回答。

屏幕

import { connect } from 'react-redux'
import { updateList } from './action'

export class List extends Component {
      constructor(props) {
        super(props);
    this.state = {
      list: this.props.list,
      name: '',
      lastname: '',
      
        };
  }


  addItem = ( name, lastname ) => {   
  
    const  item = {
        key: Math.random(),
        name: name,
        lastname: lastname,
      };
      this.setState({ list: [...this.state.list, item]})
  };

  submitItem = ( list ) => {
    () => this.props.dispatch(updateList(list));
     this.props.navigation.navigate('list');
  }

  render(){
    return(
 
        <Button onPress={() => {this.addItem(this.state.name, this.state.lastname); this.submitItem(this.state.list)}}>
         <Text>Press Submit</Text>
        </Button>

    )}

mapStateToProps = (state) => {
   return this.state
}

mapDispatchToProps = {
  updateList
}

export default connect(mapStateToProps, mapDispatchToProps)(List );

动作.JS

export const updateList = (list) => {
  return { type:"UPDATE_LIST", payload:list}
}

减速器.JS

const initialState = {
  currentUser: null,
  list: [],
};



    export const user = (state = initialState, action) => {
      switch (action.type){
          case USER_STATE_CHANGE:
            return {
              ...state,
              currentUser: action.currentUser,
            };
          case 'UPDATE_LIST': 
          return{
            ...state,
            list: [...action.payload],
          }
          default:
            return state
      }
      
    };

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


case 'UPDATE_LIST':
        return {
            ...state,
            list: action.payload,
        }

试试这个。


推荐阅读