简体   繁体   中英

Return a value before executing a function similar to setstate in react

I want to make a function that returns a value that I can check against before executing something if i need to. Similar to reacts setState. So something like:

changeState(initialState => {
  console.log(initialState);
  return 'Hello';
});

but can also be used simply like:

changeState('hello');

How is this handled? It seems like it should be simple but I for some reason can't get a grasp on how to pull this off. Does anyone know how react handles this situation.

I'm not 100% clear what you are wanting to accomplish but checking the typeof the arguments is probably what you are looking for.

Simple example that assigns an object property value based on function or primitive as first argument

 const state = { foo: 1 } const changeFoo = (...args) => { if (typeof args[0] === 'function') { // assign value as result of function passing in initial value state.foo = args[0](state.foo) } else { // assign value directly state.foo = args[0] } }; // set value directly changeFoo(2) console.log('after set 2:', state.foo)// expect 2 // set value as return of function changeFoo((initial) => initial + 1) console.log('after func:', state.foo)// expect 3

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