带钩子的问题:useEffect,useMutation和useState一起使用

问题描述 投票:0回答:1

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

当网格中某个单元格发生更改时,整个线对象将被写入状态。

我正在尝试使用useEffect来触发一个突变,该突变将状态的这些变化写回到数据库中,但是我在两个主要方面苦苦挣扎:

  • 该突变不会写回数据库(尽管该突变确实在graphql游乐场中起作用)
  • 了解如何仅将已更改的行发送回突变。

主要功能(的一部分)

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!, 
  $title: String, 
  $description: String, 
  $project:Int
  $category:Int
  $account:Int
  $amt:Int
  $units:Int
  $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
  }
}
`

我非常感谢您的建议。谢谢

reactjs apollo react-apollo apollo-client
1个回答
0
投票
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 ) }) };
© www.soinside.com 2019 - 2024. All rights reserved.