我正在嘗試創建一個處理程式來更新狀態。現在我有很多處理程式 - 每個組件一個。我想要做的是創建 switch 函式和一個處理程式來處理所有狀態更改。
這是 switch 函式,目前它只有一種情況:
function liftingUpStateHandler(type, e, state){
switch(type){
case 'imageClickHandler':
let array = state.bottomGalleryItems;
const index = array.findIndex((object) => object.cardId === e);
window.scrollTo({ top: 0, behavior: 'smooth' });
return ['items', [state.bottomGalleryItems[index]]]
default:
return null;
}
}
export default liftingUpStateHandler;
我正在嘗試在主 app.js 檔案中創建一個處理程式:
stateHandler = (type, e) =>{
const result = liftingUpStateHandler(type, e);
this.setState({result[1]: result[2]})
}
如果這行得通,我可以將案例添加到 LiftUpStateHandler 并僅使用一個處理程式更新狀態。
(一個統治他們):)
我現在處理的是很多這樣的功能:
loaderScreenHandler = (e) => {
this.setState({loader: e})
}
modalCloseHandler = () =>{
this.setState({noexifdatafilenames: []})
}
markerFlyerTo = (e) => {
const index = (markerFlyerHandler(e, this.state));
this.setState({ activeCard: index });
}
deleteItem = (e) => {
const result = (deleteItemHandler(e, this.state));
this.setState({ items: result[0]});
this.setState({ activeCard: 0 });
};
changeActiveCardRight = () => {
const result = (changeActiveCardRightHandler(this.state, 'right'));
this.setState({ activeCard: result });
}
changeActiveCardLeft = () => {
const result = (changeActiveCardRightHandler(this.state));
this.setState({ activeCard: result});
}
closeHandler = () => {
this.setState({ fullScreen: false})
}
...但我收到一個錯誤:
Failed to compile
./src/App.js
SyntaxError: C:\Users\S?awek\Desktop\dev\geolocapp\src\App.js: Unexpected token, expected "," (63:25)
61 | stateHandler = (type, e) =>{
62 | const result = liftingUpStateHandler(type, e);
> 63 | this.setState({result[1]: result[2]})
| ^
64 | }
65 |
66 |
這甚至可能嗎?或者我需要采取不同的方法,比如 REDUX ?
uj5u.com熱心網友回復:
this.setState({result[1]: result[2]})
要執行計算物件屬性,您需要在鍵周圍使用方括號:
this.setState({ [result[1]]: result[2] })
另外,我認為您打算使用result[0]and result[1],因此將是:
this.setState({ [result[0]]: result[1] })
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403754.html
標籤:
