简体   繁体   中英

react redux awaiting state change so i can map

I'm trying Redux for the first time where I've been previously using React and its component state system. My code below works 100% in its vanilla react component state but its not working as it should with Redux. Fortunately I know the nature of the problem but don't know how to fix it. When I comment out my 'Spinner' which is my loading gif, redux updates the state and the action is executed. My asynchronus api call is made and the payload is retrieved. But when the 'Spinner' is not commented out, its throws a type error and Cannot read property 'map' of undefined . My reducer has an empty array as its initial state and im sure everything is set up properly but maybe its my component code.

class Votes extends Component {


 componentDidMount() {
   this.props.getFoods();
 }



  render() {
    const {error, isLoaded, foods} = this.props; 
    if (error) {
      return <div>Error : {error.message}</div>;
    // } else if (!isLoaded) {
    //   return <Spinner />;
    } else {
      return (
        <div>
          <h2>Menu</h2>
                    <ul>
                {foods.map(food=> (
                <li key={food._id}>
                    <div className="description">
                            <h4>{food.foodname}</h4>
                    </div> 
                </li>

                ))}

            </ul>
        </div>
      );
    }
  }
}

const mapStateToProps = state => ({
  foodReducer: state.foodReducer.foods
});

export default connect(mapStateToProps, {getfoods})(FoodComponent);

heres my initalState from my reducer file:

const initialState = {
   error: null,
   isLoaded: false,
   foods: [],
}

I don't think I need to provide my actions, store or reducer as it works if spinner is commented out but if you need to see that code to decipher this problem, I can make a future edit. thanks.

In mapStateToProps, assigned foodReducer. But get value from props is foods, Please try "foodReducer"

Use "const {error, isLoaded, foodReducer } = this.props;" instead of "const {error, isLoaded, foods } = this.props; "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM