我有一些状态和它们的setState。但我想将类组件转换为功能组件,但我不明白在setState中如何实现
状态:
constructor(posts) {
super(posts);
this.state = {
data: posts,
searchResultArray: [],
cursor: {},
currentResultIndex: 0,
};
this.onToggle = this.onToggle.bind(this);
}
设置状态:
plz,看看this.setState我的观点是如何转换那些setState中的功能组件?我不明白如何在this.setState函数中进行多重状态。我能在功能组件中做到这一点吗?
onTextChange = (e) => {
const { data } = this.state;
let term = e.target.value;
let tempObj = {};
let results = [];
let newData = {};
if (term.length > 0) {
results = getSearchResult(term, data);
console.log(results);
}
if (results.length > 0) {
tempObj = setSearchResult(data, results, 0);
newData = tempObj.data;
} else {
newData = data;
}
this.setState({
searchResultArray: results,
data: newData,
searchTerm: term,
});
};
onBtnClick = (e) => {
const { data, searchResultArray, currentResultIndex } = this.state;
let index = 0;
let tempObj = {};
if (e.target.id === "prev") {
index = currentResultIndex - 1;
tempObj = setSearchResult(data, searchResultArray, index);
this.setState({
data: tempObj.data,
currentResultIndex: index,
cursor: tempObj.cursor,
});
}
if (e.target.id === "next") {
index = currentResultIndex + 1;
tempObj = setSearchResult(data, searchResultArray, index);
this.setState({
data: tempObj.data,
currentResultIndex: index,
cursor: tempObj.cursor,
});
}
};
要将其更改为功能组件,应该使用useState钩子。基本上,useState钩子用于存储状态变量并在以后更新它,您不需要再使用类状态了。有两种方法可以将您的状态转换为useState,要么使用一个大的useState,它将存储一个与您当前状态类似的变量。或者你可以把你的状态分成小块(这更干净,也是你在功能反应中应该做的方式(
以下是您的操作方法:
const [data, setData] = useState(posts);
const [searchResultsArray, setSearchResultsArray] = useState();
const [cursor, setCursor] = useState();
const [currentResultIndex, setCurrentResultIndex] = useState();
然后,在您的onClick:
onBtnClick = (e) => {
const { data, searchResultArray, currentResultIndex } = this.state;
let index = 0;
let tempObj = {};
if (e.target.id === "prev") {
index = currentResultIndex - 1;
setCurrentResultIndex(index)
tempObj = setSearchResult(data, searchResultArray, index);
setData(tempObj.data)
setCursor(tempObj.cursor)
}
if (e.target.id === "next") {
index = currentResultIndex + 1;
setCurrentResultIndex(index)
tempObj = setSearchResult(data, searchResultArray, index);
setData(tempObj.data)
setCursor(tempObj.cursor)
}
};