gpt4 book ai didi

javascript - React Hooks setState 的意外结果

转载 作者:行者123 更新时间:2023-11-30 09:12:05 25 4
gpt4 key购买 nike

我得到了一些意想不到的结果。看着那个

import React from 'react';
import PropTypes from 'prop-types';

const propTypes = {
fooList: PropTypes.array
};

const defaultProps = {
fooList: [
{ active: false },
{ active: false }
];
};

const FooBar = ({
fooList
}) => {
const [state, setState] = React.useState(fooList);
const onClick = (entry, index) => {
entry.active = !entry.active;
state[index] = entry;
console.log('#1', state) // <- That loggs the new State properly!
setState(state);
}
console.log('#2', state) // <- That does not log at after clicking on the text, only after the initial render
return state.map((entry, index) => {
return <p
onClick={() => onClick(entry, index)}
key={index}>
{`Entry is: ${entry.active ? 'active' : 'not active'}`}
</p>
})
}

FooBar.defaultProps = defaultProps;
FooBar.propTypes = propTypes;
export default FooBar;

我希望每次点击 <p /> 中的文本要从 Entry is: not active 更改的标签至 Entry is: active .

现在,我不确定我是否可以像这样简单地改变状态

state[index] = entry;

使用类扩展 React.Component ,这是行不通的。但也许使用 React Hooks?然后,我不确定我是否可以在 map() 中使用钩子(Hook).

最佳答案

当你使用 state[index] = entry; 时,你正在改变状态但状态引用没有改变,所以 React 将无法判断状态是否改变,并且会不重新渲染。

你可以在改变它之前复制状态:

  const onClick = (entry, index) => {
entry.active = !entry.active;
const newState = [...state];
newState[index] = entry;
console.log(newState) // <- That loggs the new State properly!
setState(newState);
}

关于javascript - React Hooks setState 的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com