如何在 React 列表 onClick 中更改 object 的状态?

How can I change state of object in a React list onClick?

我有一个 Objects 的列表,如下所示:

const List = [
  {
    title: " ",
    timestamp: 500,
    seen: false
  },

  {
    title: " ",
    timestamp: 600,
    seen: false
  },

列表显示为带有标题和图标的列表按钮。单击 Button 时,object 应标记为“seen: true”并且图标应更改颜色。我的问题:在我的追逐中,图标只在组件重新渲染时改变颜色,但它应该在单击按钮时改变。有人可以帮忙吗?


const styles: Styles = {
  icon_unseen: {
    color: "#f97671",
  },
  icon_seen: {
    color: "#bdbdbd",
  }
};

export const  = () => {


  const sortedList = List.sort((a, b) => a.timestamp - b.timestamp);

  const onClick = (event: any) => {
     List.map((item) =>item.timestamp==event.currentTarget.id? item.seen=!item.seen : "")
      };

return (
 <Box>
      <PopperUnstyled>
        <StyledPopperDiv>
          {sortedNList.map((element) => (
            <ListItemButton id={element.timestamp} 
                            onClick={onClick} 
                            sx={{borderRadius: 2}}>
            <ListItem>
            <ListItemText
                  primary={<Typography>{element.title}</Typography>
            />
            <FiberManualRecordRoundedIcon sx={element.seen ? styles.icon_seen : styles.icon_unseen}/>
            </ListItem>
            </ListItemButton>
            <ListItemText
                  primary={<Typography>{element.title}</Typography>
            />
            <FiberManualRecordRoundedIcon sx={element.seen ? styles.icon_seen : styles.icon_unseen}/>

          ))}
        </StyledPopperDiv>
      </PopperUnstyled>
    </Box>
  );
};

我不确定 'List' 的来源,但如果它在组件中定义,您需要 link 它到组件的状态。

const [list, setList] = useState(List);

当你想更新它时,你可以通过 setList 来完成。

setList((prevState => ({
    ...prevState, 
    Your changes
}))

This also means that inside the JSX, you use list instead of List. 

修改这三个地方使其生效:

// Assume you have fetched data from server and sorted

// Ideally, this should be inside of your data fetching function, not in the component
const sortedList = List.sort((a, b) => a.timestamp - b.timestamp); 

// 1.
const [sortedNList, setSortedNList] = useState(sortedList);

// 2.
const onClick = (timestamp) => { // We don't need to take the event as param here, but timestamp instead
  setSortedNList(sortedNList.map((item) => item.timestamp === timestamp ? {...item, seen: !item.seen} : item))
};

// 3.
{sortedNList.map((element) => (
  <ListItemButton 
    id={element.timestamp} 
    onClick={() => onClick(element.timestamp)} // pass in element's timestamp
    sx={{borderRadius: 2}}>
  ...
)}

资源推荐:React Beta docs