簡體   English   中英

如何使用React Hooks重構現有代碼?

[英]How to use React Hooks to refactor existing code?

我一直在查看React Hooks函數,並對如何准確使用useState和useEffect重構現有代碼有些猶豫。

例如,我有一個像這樣的老式組件:

class MyFunction extends React.Component{
  state = {
    count1: 0,
    count2: 0
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    return {count1: nextProps.value1, count2: nextProps.value2}
  }

  handleChange1 = ({target: {value}}) => {
    this.setState({count1: value});
    this.props.onCount1Change(value);
  }

  handleChange2 = ({target: {value}}) => {
    this.setState({count2: value});
    this.props.onCount2Change(value);
  }

  componentDidUpdate(){
    this.props.someRandomStuffs(this.state.count1, this.state.count2);
  }

  render(){
    return (
      <div>
        <input type="text" value={this.state.count1} onChange={this.handleChange1} />
        <input type="text" value={this.state.count2} onChange={this.handleChange2} />
      </div>
    )
  }
}

現在,我准備了一個解決方案來像這樣重構它。

function MyFunction(value1, value2, onCount1Change, onCount2Change, someRandomStuffs){
  const [count1, setCount1] = useState(value1);
  const [count2, setCount2] = useState(value2);

  useEffect(() => someRandomStuffs(count1, count2));

  function on1Change ({target: {value}}){
    setCount1(value);
    onCount1Change(value);
  }

  function on2Change ({target: {value}}){
    setCount2(value);
    onCount2Change(value);
  }

  return(
    <div>
      <input type="text" value={count1} onChange={on1Change} />
      <input type="text" value={count2} onChange={on2Change} />
    </div>
  );
}

以上重構足夠接近嗎? 我想知道是否可以遵循它來重構項目中的其他類。

您轉換后的組件將如下所示。 我認為您不需要更多的getDerivedStateFromProps

const myFunction = (props) => {
  const [count1, setCount1] = useState(0)
  const [count2, setCount2] = useState(0)

  const handleChange1 = ({ target: { value } }) => {
    setCount1(value)
    props.onCount1Change(value)
  }

  const handleChange2 = ({ target: { value } }) => {
    setCount2(value)
    props.onCount2Change(value)
  }

  useEffect(() => {
    props.someRandomStuffs(count1, count2);
  }, [])

  return (
    <div>
      <input type="text" value={count1} onChange={handleChange1} />
      <input type="text" value={count2} onChange={handleChange2} />
    </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM