我最近发现了我的问题,但还没有解决,所以我有一个名为 data 的变量,它有一堆对象数组,我想将它移动到全局变量,这样它就不会重新渲染,但我不能,因为 fetchedData 状态阻止我这样做,我不能将我的状态移动到全局变量,我尝试了几种方法,比如在它的组件之外创建一个函数或使用 react.memo 但是它什么也解决不了。有没有办法做到这一点?
这是我的代码Table.js:
import DataTable from "react-data-table-component";
import Columns from "./Columns.js";
...
const Table = () => {
let [page, setPage] = useState(1);
const [fetchedData, setFetchedData] = useState([]);
var [selectedRowsData, setSelectedRowsData] = useState();
const classes = useStyles();
const dispatch = useDispatch();
const checkBoxProps = {
color: "primary",
};
useEffect(() => {
const fetchAPI = async () => {
setFetchedData(
await dispatch(
fetchTableList(
localStorage.getItem("userId"),
localStorage.getItem("auth"),
page
)
)
);
};
fetchAPI();
}, [page]);
const data = [
...fetchedData.map((val, i) => ({
no: val.ROW_NUMBER,
customerId: val.CUSTOMER_ID,
customerName: val.CUSTOMER_NAME,
poDate: val.PO_DATE,
branchId: val.BRANCH_ID,
passangerId: val.PASSANGER_ID,
passangerBank: val.PASSANGER_BANK_NAME,
passangerBankBranch: val.PASSANGER_BANK_BRANCH,
created: val.CREATEBY,
})),
];
const handleChange = (state) => {
console.log(state.selectedRows);
};
return (
<div>
<TableHeader />
<div>
<div>
<DataTable
columns={Columns}
data={data}
selectableRows
selectableRowsComponent={Checkbox}
selectableRowsComponentProps={checkBoxProps}
onSelectedRowsChange={handleChange}
noDataComponent={"Fetching data, please wait..."}
selectableRowsHighlight
customStyles={CustomTableStyle}
conditionalRowStyles={CustomRowBackColor}
dense
/>
<div className={classes.footer}>
<Footer />
<div className={classes.paginationBox}>
<Pagination
nextPage={nextPage}
previousPage={previousPage}
page={page}
setPage={setPage}
/>
</div>
</div>
</div>
</div>
</div>
);
};
export default Table;```
答案 0 :(得分:2)
useMemo
可用于控制何时应重新计算功能组件内给定变量的值,例如
const data = useMemo(() => {
return [
...fetchedData.map((val, i) => ({
no: val.ROW_NUMBER,
customerId: val.CUSTOMER_ID,
customerName: val.CUSTOMER_NAME,
poDate: val.PO_DATE,
branchId: val.BRANCH_ID,
passangerId: val.PASSANGER_ID,
passangerBank: val.PASSANGER_BANK_NAME,
passangerBankBranch: val.PASSANGER_BANK_BRANCH,
created: val.CREATEBY,
})),
];
}, [fetchedData])