我有一個專案,上面有一個“登錄”頁面,用戶點擊“登錄”后,應該會出現一個界面,其中包含該用戶的所有串列。
為了在登錄程序后立即顯示此資料,我使用了“useEffect”并使用了與后端連接的“GetAllListsAction”操作來獲取資料。
請注意,我正在使用打字稿。
搜索后發現有幾個站點寫了這個邏輯,他們在“使用效果”中使用“useState”然后使用“setList”。
就像我從一個網站得到的這個例子:
const [list, setList] = useState([]);
useEffect(() => {
let mounted = true;
getList()
.then(items => {
if(mounted) {
setList(items)
}
})
return () => mounted = false;
}, [])
但是我將 React 與 TypeScript 一起使用,并且我的編碼方法因在站點內編碼而略有不同。
問題或問題是我不知道他們為什么在 useEffect 中使用 (setList) 并且我不知道如何將它添加到我的代碼中。
我的代碼是:
import { Grid } from "@material-ui/core";
import SingleList from "./single-list";
import { useStyle } from "../../../../styles/list-styles";
import Header from "../../header-footer/header";
import ListModal from "../modals/list-modal";
import { useEffect } from "react";
import { bindActionCreators } from "redux";
import { Actions } from "../../../../redux-store/actions/actions";
import { connect } from "react-redux";
import { ListItem } from "../../../../redux-store/reducers/todo-list-reducer";
const Lists: React.FC<{ TodoListList: any; GetAllListsAction: Function }> = ({
GetAllListsAction,
TodoListList,
}) => {
const classes = useStyle();
useEffect(() => {
// call action to fetch lists
GetAllListsAction();
}, []);
return (
<>
<Header />
<Grid className={classes.grid}>
<Grid
container
className={classes.addButton}
item
direction="row-reverse"
>
<ListModal />
</Grid>
<Grid container item lg={12} direction="row" spacing={1}>
{TodoListList.map((l: ListItem, index: number) => (
<Grid key={index} item lg={3} sm={6} xs={12}>
<SingleList title={l.title || ""} tasks={l.tasks} />
</Grid>
))}
</Grid>
</Grid>
</>
);
};
function mapDispatchToProps(dispatch: any) {
return bindActionCreators(
{
...Actions,
},
dispatch
);
}
function mapStateToProps(state: any) {
console.log("state inside lists component, bottom:", state);
console.log("TodoListList, bottom:", state.todoList?.List);
return {
TodoListList: state.todoList?.state || [],
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Lists);
uj5u.com熱心網友回復:
在你的例子中,獲取資料的函式和資料串列是通過 props 傳遞的。所以你不需要使用 useState。
如果在Lists組件中進行 api 呼叫,則應使用 useState 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398182.html
