gpt4 book ai didi

reactjs - 在 AgGridColumn onCellClicked 函数中 react Hook useState

转载 作者:行者123 更新时间:2023-12-04 03:56:15 24 4
gpt4 key购买 nike

目前,我正在使用带有 React Hook 的功能性 React 组件 useState和一个 AgGridReact组件。

我正在显示一个 AgGridReact并放一个 onCellClickedAgGridColumn 上运行.到目前为止一切正常。在onCellClicked函数我想更新我的状态并根据它的当前值做一些事情。

问题是:

如果我想在 useState 中使用我的状态获取/设置( onCellClicked 钩子(Hook))功能它没有按预期工作。由于某种原因,我无法更新我的状态。

在 React 类组件中它正在工作。

编辑:我试验了一段时间,发现在 onCellClicked函数 我在 myText 中只有默认值。我可以更新一次。如果我向 onCellClicked 发送垃圾邮件函数它将文本再次附加到 useState("default myText"); 的默认值.我希望字符串会随着我单击单元格的频率而变长。就像在我的类组件示例中一样。如果我在 AgGridReact 之外使用一个简单的按钮<button onClick={() => setMyText(myText + ", test ")}>add something to myText state</button>它按预期工作,每次单击我的 <button> 时字符串都会变长.如果我通过 <button> 更改 myText 的状态在AgGridReact之外然后再次点击单元格功能之前通过我的 <button> 设置的状态丢失了。

React 钩子(Hook)组件示例:

import React, { useState } from 'react';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

function App() {
const [myText, setMyText] = useState("default myText");
const [todoListRowData, setTodoListRowData] = useState([]);

// ....fetch data and set the todoListRowData state....

const myCellClickFunction = (params, x) => {
// here is the problem:
// no matter how often I click in the cell myText is every time the default value 'default myText'
// EDIT: I found out I can update the state here but only from the initial default value once, myText is on every cell click again "default myText" and will be concatenated with "hookCellClicked". So every time I click this cell the state gets again "default myTexthookCellClicked"
console.log(myText);
setMyText(myText + "hookCellClicked");
}

return (
<div className="ag-theme-alpine" style={{ height: '600px', width: '100%' }}>
<AgGridReact rowData={todoListRowData} >
<AgGridColumn headerName="ID" field="id" maxWidth="50"></AgGridColumn>
<AgGridColumn headerName="UserId" field="userId" maxWidth="85"></AgGridColumn>
<AgGridColumn headerName="Title" field="title" minWidth="555"></AgGridColumn>
<AgGridColumn headerName="completed" field="completed"></AgGridColumn>
<AgGridColumn headerName="Testcol" onCellClicked={(params) => myCellClickFunction(params)}></AgGridColumn>
</AgGridReact>
</div>
}
export default App;

如果我在类组件中做完全相同的事情,它工作正常。

示例类组件:

import React from 'react';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myClassComponentRowData: [],
testState: "defaul testState"
};
}

// ....fetch data and set ag grid rowData state....

handleCellClick = (params) => {
// here everything works just fine and as expected
// every time I click on the cell the state testState updates and it is added ", handleCellClick" every time
console.log(this.state.testState);
this.setState({testState: this.state.testState + ", handleCellClick"});
}

render() {

return <div className="ag-theme-alpine" style={{ height: '600px', width: '100%' }}>
<AgGridReact rowData={this.state.myClassComponentRowData} >
<AgGridColumn headerName="ID" field="id" maxWidth="50"></AgGridColumn>
<AgGridColumn headerName="UserId" field="userId" maxWidth="85"></AgGridColumn>
<AgGridColumn headerName="Title" field="title" minWidth="555"></AgGridColumn>
<AgGridColumn headerName="completed" field="completed"></AgGridColumn>
<AgGridColumn headerName="Testcol" onCellClicked={(params) => this.handleCellClick(params)}></AgGridColumn>
</AgGridReact>
</div>
}
}

export default MyClassComponent;

我做错了什么吗?我想使用带有 React 钩子(Hook)的功能组件。

最佳答案

除了回调 myCellClickFunction 引用了在先前的渲染调用中捕获的旧状态 myText 之外,您问题中的代码没有任何问题。如果您登录渲染方法,您可以看到状态已正确更新。这个问题称为过时关闭

function App() {
const [myText, setMyText] = useState("default myText");
const [todoListRowData, setTodoListRowData] = useState(rowData);

console.log("render", myText); // prints the latest myText state
...
}

可以看我的另一个回答here关于在使用 React hook 时如何在回调中获取最新状态。这是一个供您尝试的示例。

function useExtendedState(initialState) {
const [state, setState] = React.useState(initialState);
const getLatestState = () => {
return new Promise((resolve, reject) => {
setState((s) => {
resolve(s);
return s;
});
});
};

return [state, setState, getLatestState];
}

function App() {
const [myText, setMyText, getLatestMyText] = useExtendedState(
"default myText"
);
const myCellClickFunction = async (params) => {
setMyText(params.value);
const text = await getLatestMyText();
console.log("get latest state in callback", text);
};
...
}

现场演示

Edit AgGrid Get Latest State In Callback

关于reactjs - 在 AgGridColumn onCellClicked 函数中 react Hook useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63857717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com