Hook 的问题:useEffect、useMutation 和 useState 一起工作

Problem with Hooks: useEffect, useMutation and useState working together

我有一个使用 react-table 作为数据网格的函数。它最初是通过本地状态从父组件中的 Apollo 填充的,网格中的每一行都是数组中的一个对象。

当网格中的单元格发生变化时,整个线对象将写入状态。

我正在尝试使用 useEffect 来触发将这些状态变化写回数据库的突变,但我正在努力解决两个主要问题:

主要函数(部分)

function Table2({ columns, data }) {
  const [lines, setLines] = useState(data);
  const [updateLine, {loading, error }] = useMutation(UPDATE_ITEM_MUTATION, {
  variables:{ ...lines}
  });

  useEffect(() => {
    updateLine
  },[lines]);

  const updateMyData = (rowIndex, columnID, value) => {
    setLines(getLines =>
      getLines.map((row, index) => {
        if (index === rowIndex) {
          console.log(row)
          return {
            ...lines[rowIndex],
            [columnID]: value
          };
        }
        return row;

      })
    );
  };

和突变...

const UPDATE_ITEM_MUTATION = gql`
mutation UPDATE_LINE_MUTATION(
  $id: ID!, 
  $description: String, 
  $project:Int
  $category:Int
  $account:Int
  $amt:Int
  $units:String
  $multiple:Int
  $rate:Int
  ){
  updateLine(
    where:{id: $id},
    data: {
    description: $description
    project: $project
    category: $category
    account: $account
    amt: $amt
    units: $units
    multiple: $multiple
    rate: $rate
    }) {
    id
    description
    amt
  }
}
`

如果能提供一些建议,我将不胜感激。 谢谢

我认为你不需要使用useEffect,你可以在你的更新中触发突变:

function Table2 ({ columns, data }) {
  const [lines, setLines] = useState(data)
  const [updateLine, { loading, error }] = useMutation(UPDATE_ITEM_MUTATION)

  const updateMyData = (rowIndex, columnID, value) => {
    const updatedLine = { ...lines[rowIndex], [columnID]: value }
    updateLine({ variables: { ...updatedLine } })
    setLines(getLines => getLines.map((row, index) => (index === rowIndex ? updatedLine : row)))
  }
}

如果您确实想要使用 useEffect,您可以将最后更改的行保存在状态变量中,然后使用它来触发更新:

function Table2 ({ columns, data }) {
  const [lines, setLines] = useState(data)
  const [updateLine, { loading, error }] = useMutation(UPDATE_ITEM_MUTATION)
  const [updatedLine, setUpdatedLine] = useEffect(null);
  useEffect(()=>{
     // call your mutation
  }, [updatedLine]);
  const updateMyData = (rowIndex, columnID, value) => {
    const updatedLine = { ...lines[rowIndex], [columnID]: value }
    setUpdatedLine(updatedLine);
    updateLine({ variables: { ...updatedLine } })
    setLines(getLines => getLines.map((row, index) => (index === rowIndex ? updatedLine : row)))
  }
}