我是 React 的新手。我有一個我創建的評級組件。我遇到的問題是 onClick 我可以看到評級正在控制臺中更新,但在頁面上我沒有看到發生的變化。我的理解是 React 組件需要是純函式,并且最好選擇函陣列件而不是類。當我嘗試使用 useState 鉤子時,我的評分被添加到以前的狀態并且沒有在頁面上正確更新。
我的第一個問題是在組件內更新狀態的最佳/首選方法是什么?如果我使用的是功能組件,我是否必須使用鉤子?
請看下面我的代碼
export default function Rating(props) {
let stars = [];
// const [stars, setStars] = useState([]);
let star = '☆';
for (let i = 0; i < props.stars; i ) {
stars.push(star);
}
function rate(index) {
let filledStar = '★'
let stars = [];
// setStars([])
for (let i = 0; i < props.stars; i ) {
stars.push(star);
}
stars.forEach((star, i) => {
while (index >= 0) {
stars[index] = filledStar;
index--;
}
})
console.log('stars filled', stars)
return stars
}
return (
<>
<div className="stars">
{stars.map((star, i) => (
<h2
key={i}
onClick={() => rate(i)}>{star}
</h2>
))}
</div>
</>
)
}

如果我單擊第四顆星,它會按預期回傳,但 UI 不會更新。
uj5u.com熱心網友回復:
正如您所建議的,您將需要使用鉤子來尋找您正在尋找的功能(或使用類組件)。在您當前的實作中,您實際上并未使用 React 狀態,因此 React 不知道您希望它重新渲染您的組件。此外,您在 rate() 中使用的星形陣列與組件中的星形陣列不同。您似乎沒有使用由 rate() 創建和回傳的 stars 陣列
你究竟是如何嘗試使用 useState 的?
uj5u.com熱心網友回復:
這是一個作業版本,它填充星星,包括被點擊的星星 - 使用useState, 和useEffect。
const { Fragment, useEffect, useState } = React;
function Rating(props) {
// Set state as an empty array
const [stars, setStars] = useState([]);
// Called by useEffect his function
// creates a new array of empty stars
function initStars() {
const stars = [];
for (let i = 0; i < props.stars; i ) {
stars.push('☆');
}
setStars(stars);
}
// Called when the component
// first mounts, and called only once
useEffect(() => {
initStars();
}, []);
function rate(e) {
// Get the id from the star dataset
const { id } = e.target.dataset;
// Create a fresh array
const stars = [];
// Loop; if the current index is less or
// equal to the id set it as a filled star
// otherwise set it to an empty star
for (let i = 0; i < props.stars; i ) {
stars.push(i <= id ? '★' : '☆');
}
// Set the state with the new array
setStars(stars);
}
return (
<Fragment>
<div>
{stars.map((star, i) => (
<span
className="star"
key={i}
data-id={i}
onClick={rate}
>{star}
</span>
))}
</div>
</Fragment>
);
};
ReactDOM.render(
<Rating stars="10" />,
document.getElementById('react')
);
.star { font-size: 1.8em; }
.star:hover { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368949.html
標籤:javascript 反应 反应钩子 jsx
