Reactjs,钩子的类组件

问题描述 投票:0回答:1

我仍然是ReactJs的初学者。实际上,我想重写类组件以挂钩组件,但是我的一部分代码有问题。任何人都可以帮助我重写此组件以进行挂钩吗?

这是我的代码:

class App extends Component {
  state = {
    selected: {},
    data: data,
    filtered: data
  };

  handleChange = data => {
    if (data == null) {
      this.setState({
        filtered: this.state.data
      });
    } else {
      this.setState({
        selected: data,
        filtered: this.state.data.filter(d => d.client_id === data.id)
      });
    }
  };

  returnClientNameFromID = id => options.find(o => o.id === id).name;

  render() {
    const {
      state: { selected, data, filtered },
      handleChange
    } = this;


    return ( <div>
    ...
reactjs class components hook setstate
1个回答
0
投票

这是您可以做的。使用useState,您始终必须自己合并对象setState((prevState) => {...prevState, ... })

const App = () => {
  const [state, setState] = useState({
    selected: {},
    data: data,
    filtered: data
  })

  const handleChange = data => {
    if (data == null) {
      setState((prevState) => {
        ...prevState,
        filtered: this.state.data
      });
    } else {
      setState((prevState) => {
        ...prevState,
        selected: data,
        filtered: prevState.data.filter(d => d.client_id === data.id)
      });
    }
  };

  const returnClientNameFromID = id => options.find(o => o.id === id).name;

  const { selected, data, filtered } = state

  return() (
    <div> ... </div>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.