简体   繁体   中英

React setState dynamically - how to setState property and value from props

I'm trying to create a single handler to update the state. For now i have many handlers - one for every component. What i'm trying to do is create switch function and one handler to handle all state changes.

Here's the switch function, for now it has only one case:

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;

And i'm trying to create one handler in main app.js file:

  stateHandler = (type, e) =>{
    const result = liftingUpStateHandler(type, e);
    this.setState({result[1]: result[2]})
  }

If this would work i can just add cases to liftingUpStateHandler and update state with only one handler.

(one to rule them all):)

What i'm dealing now is a lot of functions like this:

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})
  }

... But i'm getting an error:

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 |

Is this even possible? Or i need to take different approach like REDUX?

this.setState({result[1]: result[2]})

To do a computed object property , you need to use square brackets around the key:

this.setState({ [result[1]]: result[2] })

Also, i think you meant to use result[0] and result[1] , so it would be:

this.setState({ [result[0]]: result[1] })

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