【问题标题】:How to remake class component to functional and state to useState if in my case I have few property in state?如果在我的情况下我的状态属性很少,如何将类组件重新制作为功能和状态为 useState?
【发布时间】:2020-04-18 18:07:34
【问题描述】:

有一个类组件需要remake to functional和state remake to useState hook。但是状态几乎没有属性:

class App extends React.Component {

  state = {
    num: 0,
    text: 'no',
    textUpper: 'HELLO'
  }

  changeState = () => {
    this.setState({
      num: this.state.num + 1,
      text: "yes",
      textUpper: 'BYE'
    });
  }

  render() {
    return (
      <div>
          <button onClick={this.changeState}>like</button>
          {this.state.num}
          {this.state.text}
          {this.state.textUpper}
      </div>
    );
  }
}

我知道如果它只有一个属性,它看起来像这样:

const App = () => {
      const [num, setNum] = useState(0);

      const changeState = () => {
           setNum(num+1);
       }

    return (
      <div>
            <button onClick={changeState}>like</button>
           {num}
      </div>
    );
}

但是当我的属性很少时如何重新制作我的组件,就像我不知道的情况一样。请告诉我。

【问题讨论】:

  • 这能回答你的问题吗? useState to update multiple values in React
  • @Anurag Srivastava 不,这与我的问题非常不同!你看另一个问题吗?还是只看标题?他通常会在那里询问注册。
  • 状态中有多个值,答案显示了如何在功能组件中执行此操作。或者您是否期待从头开始编写功能组件的演练?
  • @Anurag Srivastava 我想看看如果他是双功能的,我的组件会是什么样子

标签: reactjs


【解决方案1】:

您可以在 useState 中使用对象作为值...

// Set up your state
const [value, setValue] = useState({
   num: 0,
   text: "no",
   textUpper: "HELLO"
});

// Later on to update
setValue({
    num: value.num + 1,
    text: "yes",
    textUpper: "BYE"
});

需要注意的重要一点是,使用setValuethis.setState 略有不同。 setValue 将替换整个值,就像这样......

this.state = {
    a: "Hello",
    b: "World"
}

this.setState({
    a: "Goodbye"
})

// this.state = { a: "Goodbye", b: "World" }
const [value, setValue] = useState({
    a: "Hello",
    b: "World"
})

setValue({
    a: "Goodbye"
})

// value = { a: "Goodbye" }

您也可以将多个 useState 挂钩与单个值一起使用。

// Set up your state
const [num, setNum] = useState(0);
const [text, setText] = useState("no");
const [textUpper, setTextUpper] = useState("HELLO");

// Later on to update
setNum(num + 1);
setText("yes");
setTextUpper("BYE");

这真的取决于您和您的用例来确定最佳方法。祝你好运!

【讨论】:

  • 好的,但是想象一下,当我单击按钮时,我需要更改状态的所有属性。因此,告诉我如何将我的组件转换为函数式
  • 好的,更新了第一个和最后一个代码块,向您展示如何根据您的问题更新状态。
  • 如果我这样写:i.piccy.info/i9/2770aac2c1d62cf3c0c17e2dda99dea3/1587236826/… 我有这个错误:Line 24:8: 'num' is not defined no-undef Line 25:8: 'text' is not defined no-undef Line 26:8: 'textUpper' is not defined no-undef 为什么?
  • 因为您的状态现在在value 内继续。第 24、25 和 26 行需要更新:{value.num} {value.text} {value.textUpper}
猜你喜欢
  • 2018-05-27
  • 2021-12-06
  • 2021-03-01
  • 1970-01-01
  • 2018-09-29
  • 2017-01-16
  • 2019-07-18
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多