如果在我的情况下,状态中几乎没有属性,如何将类组件重制为functional,并将状态重制为useState



有一个类组件需要重制版才能正常工作,需要状态重制版才能使用state钩子。但国家几乎没有什么属性:

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中使用对象作为值。。。

// 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");

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

最新更新