【问题标题】:Update state that depends on other calculated state in React-Hooks更新依赖于 React-Hooks 中其他计算状态的状态
【发布时间】:2019-10-25 05:46:49
【问题描述】:

我想更新一个依赖于其他计算状态(服务器)的状态(数据)

 setServer(prevTweets =>
          [...json, ...prevTweets].filter(
            (e, i, arr) => i === arr.findIndex(t => t.tweetId === e.tweetId)
          )
  )

上面的数据将用于设置下面的状态(数据):

let totalPositive = 0;
        let totalNegative = 0;
        let totalNeutral = 0;
        server.forEach(tweet => {
          if(tweet.sentiment >0) totalPositive++;
          if(tweet.sentiment < 0) totalNegative++;
          if(tweet.sentiment ===0) totalNeutral++;
        })

setData([
       { name: 'Positive', value: totalPositive },
       { name: 'Negative', value: totalNegative },
       { name: 'Neutral', value: totalNeutral },
 ])

由于是异步的,setData 操作总是迟到。我知道我可以使用 useEffect 但显然它会造成无限循环,在这种情况下使用它是不对的。

【问题讨论】:

  • 如果我做对了,那么您使用的服务器值是setData。只需观察server 的变化,您就可以使用 setData 逻辑 useEffect。如果您可以添加相同的基本代码和框示例,那就太好了。
  • 您可以尝试将服务器传递给设置数据的函数,然后在设置服务器之前调用该函数:newServer=[...json,...pref]...;functionToSetData(newServer);setSerer(newSerer)

标签: reactjs react-hooks


【解决方案1】:

如果在设置服务器之前设置新数据,则会跳过一次渲染:

//still defaults to server so if you do't pass anything it;s still the same
const setNewData = (newServer = server) => {
  const [
    totalPositive,
    totalNegative,
    totalNeutral,
  ] = newServer.reduce(
    ([pos, neg, neu], { sentiment }) =>
      sentiment > 0
        ? [pos + 1, neg, neu]
        : sentiment < 0
        ? [pos, neg + 1, neu]
        : [pos, neg, neu + 1],
    [0, 0, 0]
  );

  setData([
    { name: 'Positive', value: totalPositive },
    { name: 'Negative', value: totalNegative },
    { name: 'Neutral', value: totalNeutral },
  ]);
};

setServer(prevTweets => {
  const newServer = uniqueByTweetId([
    ...json,
    ...prevTweets,
  ]);
  setNewData(newServer);
  return newServer;
});

与问题无关但可能重要的是,您获得独特价值的方式可以得到改善。您可以一次获得唯一值,而无需多次调用 find index:

const uniqueBy = getter => arr => {
  const items = new Map();
  return arr.filter(item => {
    const key = getter(item);
    const ret = items.get(key);
    items.set(key,true);
    return !ret;
  });
};
const data = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 4 },
  { id: 5 },
  { id: 1 },
  { id: 7 },
  { id: 1 },
  { id: 7 },
  { id: 8 },
  { id: 1 },
];
const uniqueById = uniqueBy(i => i.id);
console.log(uniqueById(data));

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多