[英]React : Prop not updated inside of a map function
這是我的父組件的簡化版本:
export default function Parent() {
// State
const [status, setStatus] = useState(1);
const [source, setSource] = useState('https://packagingeurope.com/downloads/7475/download/danone-05.03.20.jpg');
const [steps, setSteps] = useState([
{
title: 'Prediction Initiated',
value: 1,
loading: false,
completed: false,
active: false,
},
{
title: 'Prediction in Progress',
value: 2,
loading: false,
completed: false,
active: false,
},
{
title: 'Prediction Finished',
value: 3,
loading: false,
completed: false,
active: false,
},
]);
useEffect(() => {
if (status) {
const newSteps = steps;
newSteps[status - 1].active = true;
if (status > 1) {
newSteps[status - 2].completed = true;
}
if (status === 3) {
newSteps[status - 1].active = false;
newSteps[status - 1].completed = true;
}
setSteps(newSteps);
} else {
// Do nothing
console.log('No status match');
}
},
[status]);
return (
<div className="container-fluid">
<Timeline status={status} steps={steps} source={source} />
</div>
);
}
這是我的子組件:
export default class Timeline extends React.Component {
renderSteps() {
const { steps } = this.props;
return steps.map((step, index) => {
console.log(step);
console.log(steps);
return (
<div key={`test${index}`}>
{step.title}
{step.active && <span>is active</span>}
{step.loading && <span>is loading</span>}
{step.completed && <span>is completed</span>}
</div>
);
});
}
render() {
const { status, steps, source } = this.props;
return (
<div className="timeline">
{this.renderSteps()}
</div>
</>
);
}
}
當我在子組件中執行 console.log steps
道具時,我看到它們已正確更新。 (當status === 1時,第一步active
屬性為true
)
但是當我執行 console.log step
(在我的 map 函數中)時,沒有更新任何屬性。 (當status === 1時,第一步active
屬性為false
)
您可以在下面的捕獲中看到有些地方不對(我已經遇到過這個問題,但不幸的是我不記得我是如何解決它的,我想知道這是否是因為我在這個項目之前沒有使用的useEffect
掛鈎.
謝謝您的幫助
好的,我想通了。
由於我從另一位開發人員那里得到了這段代碼,所以我並不了解所有已實現的內容。 我查看了 React 文檔以了解問題出在哪里。
通過將第二個參數傳遞給useEffect
function, React 可以跳過效果,並且如果沒有任何更改,則不會因性能問題重新渲染組件。 由於我的狀態沒有改變(我暫時手動更改它),我的組件沒有刷新。
通過在第二個參數中添加[steps]
width [status]
,一切正常。
useEffect(() => {
if (status) {
const newSteps = steps;
newSteps[status - 1].active = true;
if (status > 1) {
newSteps[status - 2].completed = true;
}
if (status === 3) {
newSteps[status - 1].active = false;
newSteps[status - 1].completed = true;
}
setSteps(newSteps);
} else {
// Do nothing
console.log('No status match');
}
}, [status, steps]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.