简体   繁体   English

React-Redux,如何在渲染新组件之前设置全局 state?

[英]React-Redux, How to set global state before new component is rendered?

I am currently learning react-redux and I am attempting to update the global state with an array that is fetched from an API.我目前正在学习 react-redux 并且我正在尝试使用从 API 获取的数组来更新全局 state。 When the onClick event is fired the page renders the new component before the global state can be set.当 onClick 事件被触发时,页面在全局 state 可以设置之前呈现新组件。 When NavLink is set to '#' the state is able to be set.当 NavLink 设置为“#”时,可以设置 state。 How could I have redux populate the state before rendering the new component?在渲染新组件之前,如何让 redux 填充 state?

My main objective is to pass the fetched array to a different component to display the fetched information.我的主要目标是将获取的数组传递给不同的组件以显示获取的信息。

COMPONENT零件

function Selector(props) {
  const [alcoholCategory, setAlcoholCategory] = useState([]);

useEffect(() => {
    props.handleCategorySelection(alcoholCategory);
  });

  function handleImagePress(alc) {
    fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${alc}
    `)
      .then((r) => r.json())
      .then((result) => setAlcoholCategory(result.drinks))
      .then(props.handleCategorySelection(alcoholCategory));
  }
  console.log(alcoholCategory);
  return (
    <div className="selector-div">
      <ul>
        <li>
          <NavLink to="vodka" onClick={() => handleImagePress("Vodka")}>
            <img
              src="https://hips.hearstapps.com/vader-prod.s3.amazonaws.com/1583334281-smirnoff-1583334273.png"
              alt="alcohol-bottle"
              className="selector-bottle-img"
            ></img>
          </NavLink>
          <label>Vodka</label>
        </li>
<li>
          <a href="/rum" onClick={() => handleImagePress("Rum")}>
            <img
              src="https://hips.hearstapps.com/vader-prod.s3.amazonaws.com/1583334281-smirnoff-1583334273.png"
              alt="alcohol-bottle"
              className="selector-bottle-img"
            ></img>
          </a>
          <label>Rum</label>
        </li>
        <li>
          <a href="/tequila" onClick={() => handleImagePress("Tequila")}>
            <img
              src="https://hips.hearstapps.com/vader-prod.s3.amazonaws.com/1583334281-smirnoff-1583334273.png"
              alt="alcohol-bottle"
              className="selector-bottle-img"
            ></img>
          </a>
          <label>Tequila</label>
        </li>
      </ul>
    </div>
  );
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleCategorySelection: (drinks) =>
      dispatch({ type: "DRINK_LIST", drinkArray: drinks }),
  };
};
export default connect(null, mapDispatchToProps)(Selector);

REDUCER减速器

const initialState = { drinkList: [] };

const alcoholCategory = (state = initialState, action) => {
  switch (action.type) {
    case "DRINK_LIST":
      return {
        ...state,
        drinkList: state.drinkList.concat(action.drinkArray),
      };
  }
};

export default alcoholCategory;

You could conditionally render the new component around the store property it is dependent on.您可以有条件地围绕它所依赖的 store 属性呈现新组件。

Parent Component:父组件:

import React from 'react';
import {connect} from 'redux';
import anyActionYouNeed from '../actions/anyActionYouNeed'

const mapStateToProps = state => {
  return {
    drinkList: state.drinkList,
  }
}

const mapDispatchToProps = {
  anyActionYouNeed
}

//drinkList.length > 0 in your case
let Parent = ({drinkList, anyActionYouNeed}) => {
  return(
    <div>
      {drinkList.length > 0 && <NewComponent drinkList={drinkList}/>}
    </div>
  )
}

Parent = connect(
  mapStateToProps,
  mapDispatchToProps
)(Parent)

export default Parent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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