简体   繁体   中英

React hooks object update gets strange behaviour on Safari browser

React hooks object update gets strange behaviour on Safari browser(only on Safari browser)

const [state, setState] = React.useState({
  show_welcome: true,
  show_inline: false,
  restriction: false,
  request_dp: false,
  prevent_rtl: false,
  lang: "ta"
});

setState

const handleToggle = ({ target }) => {
  setState(s => ({ ...s, [target.name]: !s[target.name] }));
};

Is there anything break the order of object for Safari browser 🤔

React hooks 对象更新在 Safari 浏览器上出现奇怪的行为

编辑 infallible-keldysh-uolgt

The reason this is happening is because it's re-rendering the array that you are using for the keys and the keys aren't in the same order as they were in the first render. You can see this by adding a console.log(state) just before the first return. Safari is more strict in this than Chrome or Firefox.

You can fix this by sorting the array before using it to render.

You can also fix this by changing your toggle function to something like this:

const handleToggle = ({ target }) => {
    const tempState = { ...state };
    tempState[target.name] = !tempState[target.name];
    setState(tempState);
  };

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