[英]How to set react state with new props immediately after calling `dispatch` via react-redux connect?
[英]React-Redux, How to set global state before new component is rendered?
我目前正在學習 react-redux 並且我正在嘗試使用從 API 獲取的數組來更新全局 state。 當 onClick 事件被觸發時,頁面在全局 state 可以設置之前呈現新組件。 當 NavLink 設置為“#”時,可以設置 state。 在渲染新組件之前,如何讓 redux 填充 state?
我的主要目標是將獲取的數組傳遞給不同的組件以顯示獲取的信息。
零件
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);
減速器
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;
您可以有條件地圍繞它所依賴的 store 屬性呈現新組件。
父組件:
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.