【问题标题】:React Hooks state is not updating with correct outputReact Hooks 状态没有更新为正确的输出
【发布时间】:2021-04-21 19:59:14
【问题描述】:

我正在使用 React Hooks。我正在尝试对从 API 获取的数据进行排序,并使用新排序的数据更新状态。

const [runs, setRuns] = useState({
    runs: [],
  });
const [altConcentrationRuns, setAltConcentrationRuns ] = useState({
    altConcentrationRuns : []
  })

async function handleRuns() {
    getRuns().then((result) => {
    
      setRuns(result.rows);
      setFilteredRuns(result.rows);

      //function to sort data according to column header/property
      
      const sortRowsByProperty = (property, direction) => {
        return result.rows.sort(function(a,b) { 
          var A = Object.keys(a)[0];
          var B = Object.keys(b)[0];
          if(direction == "ascending") {
                return (a[A][property] - b[B][property]);
              } else if(direction == "descending") {
                return b[B][property] - a[A][property];
              }
          });
        } 
        setAltConcentrationRuns(sortRowsByProperty('altConcentration', 'ascending'));
        //not updating, only showing runs 

      
      setIsLoading(false);
      
      
    });
  }

  useEffect(() => {
    setIsLoading(true);
    handleRuns();
    
  }, []);
  console.log('runs', altConcentrationRuns);

当我控制台记录我的输出时,我没有得到排序的数据,只有原始数据 (result.rows)。我做错了什么?

谢谢!

【问题讨论】:

  • 您可以在控制台中添加您获得的日志吗?
  • 未按 altConcentration 排序的对象数组,而是提取数据(运行)的原始数组
  • 请截图:)
  • altConcentration 确实是一个字符串,你不能子结构字符串,所以你应该遵循@xdumaine 的建议。另外,sort 会改变原始数组,所以当它被排序时,它会在任何地方排序

标签: javascript reactjs react-hooks state


【解决方案1】:

我在您的代码中发现了一个问题。你以错误的方式初始化你的状态。

const [runs, setRuns] = useState([]);
const [altConcentrationRuns, setAltConcentrationRuns ] = useState([])

这就是你的状态应该被初始化的方式。 useState的文档

【讨论】:

    【解决方案2】:

    问题在于您的排序功能。在 JS 中对项目进行排序,通常的做法是在 a < b 时返回 -1,在 a == b 时返回 0,在 a > b 时返回 1。您通常可以省略== 条件,只返回-11

    if (direction === "ascending") {
       return a[A][property] < b[B][property] ? -1 : 1
    } else if (direction === "descending") {
       return a[A][property] < b[B][property] ? 1 : -1
    }
    

    这可以进一步优化,但为了便于理解,请保持与您的代码相似。

    【讨论】:

    • 谢谢,但仍未排序。我在其他数据上测试了我的函数,结果很好。
    • @NadiaCibrikova 你能详细说明一下吗?您不是要求返回-101,但它们与要求中所需的negative, 0 positive 一致。我确实说过应该,因为这是最佳实践。返回 a[A][property] - b[B][property] 仅适用于数字,但 &lt; 运算符也适用于字符串。
    • 从您的回答看来,排序功能只能与-1、0和1一起使用,事实并非如此,您可以使用任何正数和负数
    • 我同意你的评论,但我评论的是你的答案,而不是评论:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多