简体   繁体   中英

React useState not rerendering

I am currently implementing a drag and drop system, in one of my js file I have implemented a functional component using React hooks, I have been working with class components, and I am not very familiar with the functional component of React.

So I know in class component, this.setState will re-render, however, when I use setState in functional component it does not re-render the component.

Here is my code

// My state declaration
const [items, setItems] = React.useState({
  row1: [],
  row2: [],
  row3: []
});

...
// This is my setItems call
setItems(prevState => {
  let tempHolder = items;
  // itemArray is a value passed down as props
  tempHold.row1 = itemArray;
  return tempObj;
});

I know that the problem causing this to happen is that React thinks my return value is the same as items , so it did not cause setItems to re-render, but I am not sure how to fix this issue.

You need to make sure the expression you return from the setter function is not === to the expression currently in state:

const [items, setItems] = React.useState({
  row1: [],
  row2: [],
  row3: []
});
// ...
setItems({
  ...items,
  row1: itemArray
});

(since the setter function is named setItems , that's the function name you should call - not setVideos )

Whether in class components or in functional components, don't mutate state - create new objects instead.

In this case, you might also consider having separate state variables, eg:

const [row1, setRow1] = useState([]);

and then you just have to call setRow1 without messing with any of the other rows.

If you have lots of rows, I think an array of arrays in state would make more sense:

const [items, setItems] = useState(() => Array.from({ length: 5 }, () => []));
// ...
setItems(items.map(
  (item, i) => i === 0 ? itemArray : item
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM