JSX回调使用旧状态值

时间:2020-10-26 11:39:50

标签: reactjs

我已经看到这个问题已经发布,但是我找不到适合我情况的任何东西。

我有这个组成部分:

const DefineConstraints = ({ data = [] }) => {
const CONSTRAINTS_EQUALITY_OPTIONS = [
  { value: '>', label: '>' },
  { value: '=', label: '=' },
  { value: '<', label: '<' },
  { value: '≤', label: '≤' },
  { value: '≥', label: '≥' }
]
const [rows, setRows] = useState([])
const [counter, setCounter] = useState(0)

const addRow = () => {
  const row = {
    constraint: <Select options={data} style={{ width: '200px' }} />,
    condition: <Select options={CONSTRAINTS_EQUALITY_OPTIONS} style={{ width: '100px' }} />,
    value: <InputNumber />,
    key: counter,
    actions: <DeleteOutlined onClick={() => remove(counter)} />
  }

  setRows([...rows, row])
  setCounter(counter + 1)
}

const remove = id => console.log(rows)

return (
  <>
    <Space style={{ marginBottom: '20px' }}>
      <strong>CONSTRAINTS</strong>
      <Button onClick={onClick}>Add</Button>
    </Space>
    <Table dataSource={rows} columns={columns} />
  </>
)
}

如您所见,我在删除图标(DeleteOutlined)的事件onClick上放置了一个回调。 回调在console.log(rows)中返回了错误的值,我想这是行生成时的状态值。实际上,如果我生成6行,这是每行控制台日志的结果

[]

[{...}]

[{...}, {...}]

[{...}, {...}, {...}]

等...

如何访问正确的状态?

0 个答案:

没有答案