我在我的 redux 存储中有一个对象列表,作为数组存储在组件挂载时加载。我想将它们列在一个div中,也做crud操作。这是我的实现。每当我使用 useSelector 保存常量的列表时,它都会影响无限数量的日志。
分支操作.js
import axios from 'axios';
export const fetchAllBranchListOk = (branchList) => {
return {
type : 'FETCH_ALL_BRANCH_LIST_OK',
branchList
}
};
export const fetchAllBranchList = () =>{
return (dispatch) => {
return axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(response => {
dispatch(fetchAllBranchListOk(response.data));
})
.catch(error => {
throw(error);
});
}
};
分支减速机
export default (state = [], action) => {
switch (action.type) {
case 'FETCH_ALL_BRANCH_LIST_OK' :
return action.branchList;
default:
return state;
}
};
分支机构管理.js
function BranchManagement() {
store.dispatch(BranchAction.fetchAllBranchList());
const AllBranch = useSelector(state => state.BranchReducer)
return(
<div>
</div>
)
}
export default BranchManagement;
组合减速器 ->指数.js
import {combineReducers} from 'redux'
import BranchReducer from "./Admin/BranchReducer";
const Reducers = combineReducers({
BranchReducer
});
export default Reducers;
如果要dispatch
操作以从支持的数据中获取数据,则应将这些调用保留在钩子useEffect
。useEffect 的目的类似于类组件中生命周期方法的目的,如componentDidMount
、componentDidUpdate
和componentWillUnMount
。要了解有关useEffect
的更多信息,请参阅此处。
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import BranchAction from "/path/to/BranchAction";
function BranchManagement() {
const dispatch = useDispatch();
//Since the data in the state is on `branchList`. You can directly return
//`state.branchList` which will you provide you the data you are looking for.
const branchList = useSelector(state => state.branchList)
//It'll act similar to `componentDidMount`. Since we are passing `[]`
//to `useEffect` dependencies array
useEffect(() => {
dispatch(BranchAction.fetchAllBranchList());
}, [])
//Here I'm assuming `branchList` is array of objects with `name` and `id`.
//Updated answer with branchList as[{"branchID":1,"createdBy":1,"isActive":true,"branchDetails":{"branchDetailsID":1}},{"branchID":2,"createdBy":1,"isActive":true,"branchDetails":{"branchDetailsID":1}}]
return(
<div>
{
(branchList || []).map((branch, index) => {
<div key={branch.branchID || index}>
<span>{branch.branchID}</span>
<span>{branch.createdBy}</span>
<span>{branch.isActive}</span>
<span>{branch.branchDetails.branchDetailsID}</span>
</div>
}
}
</div>
)
}
export default BranchManagement;
希望这有助于解决问题。