如何在React中创建一个类似于this.setState的钩子

时间:2020-06-23 17:30:35

标签: javascript reactjs react-hooks

我需要创建一个类似于this.setState的钩子,但是我不知道如何在this.setState中实现类似于回调的功能。你有什么主意吗?

std:vector<std::vector<object>> vvec;
{
    std::vector<object> v;
    v.emplace_back(object());
    vvec.push_back(v);
}
import React, { useState } from 'react';

const useSetState = (initialState) => {
  const [state, setState] = useState(initialState)
  const setPartialState = (stateToSet, callback) => {
    console.log('stateToSet: ', stateToSet);
    console.log('callback: ', callback);
    if (typeof stateToSet === 'function') {
      setPartialState(stateToSet(state));
    } else if (typeof state === 'object' &&
      typeof stateToSet === 'object' &&
      !Array.isArray(state) &&
      !Array.isArray(stateToSet)
    ) {
      setState({ ...state, ...stateToSet });
    } else {
      setState(stateToSet);
    }
  }
  return [state, setPartialState]
}


const App = () => {
  const [count, setCount] = useSetState(0);
  const checkCount = () => {
    if (count === 10) {
      console.log('Booooom!');
    }
  }
  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount((count + 1, checkCount))}>Add</button>
    </div>
  );
}

export default App;

1 个答案:

答案 0 :(得分:0)

使用React钩子时,与使用基于类的React组件相比,您需要使用不同的思维方式。

如果要在计数更改为10时执行某项操作,则应在useEffect挂钩内执行该操作。

const App = () => {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    if (count === 10) {
      console.log('Booooom!');
    }
  }, [count])

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Add</button>
    </div>
  );
}