reactjs - React Redux .map 项目,并在获取数据以显示每个项目
问题描述
我有Component
with clients list >为每个客户添加一个Child Component
with list of the client's orders。
从Child Component
我正在调用fetchClientOrders
(对于订单列表),并将它放到Parent Component
- 当我尝试setClientOrders
在中时Child Component
,我得到了一个错误"Uncaught TypeError: clientOrders.map is not a function"
为每个子组件获取数据并使用 React Redux 显示它的正确方法是什么?
谢谢!
父组件 - 客户列表
{clients.map((clientDetails, index) => {
return (
<Card key={index}>
<Accordion.Toggle as={Card.Header} eventKey={clientDetails.id}>
<Row style={{textAlign:'center'}}>
<Col style={{margin: 'auto'}} xs lg="1">{clientDetails.id}</Col>
<Col style={{margin: 'auto'}}>{clientDetails.first_name} {clientDetails.last_name}</Col>
<Col style={{margin: 'auto'}}>{clientDetails.client_type}</Col>
</Accordion.Toggle>
<Accordion.Collapse eventKey={clientDetails.id}>
<Card.Body>
>>>>>>>>>>>>>>> <ClientOrdersList clientId={clientDetails.id} />
</Card.Body>
</Accordion.Collapse>
子组件 - 客户订单
function ClientOrdersList(props) {
const [clientOrders, setClientOrders] = useState([])
const dispatch = useDispatch()
useEffect(() => {
dispatch(props.fetchClientOrders(props.clientId))
}, [props.clientId]);
return (
<div>
<Table striped bordered hover size="sm">
<thead>
<tr style={{textAlign: 'center'}}>
<th>........
操作 - fetchClientOrders
export const fetchClientOrders = (clientId) => {
return async dispatch =>{
dispatch(fetchingRequest())
try {
let response = await axios.get('http://127.0.0.1:8000/api/orders/?client_id=' + clientId)
dispatch({
type: 'FETCHING_CLIENT_ORDERS_SUCCESS',
payload: await response.data
})
} catch(error) {
console.log(error)
dispatch(fetchingFailure(error))
}
}
}
解决方案
Ciao,您的错误意味着这clientOrders
不是一个数组(您可以在其上调用.map
函数)。发生这种情况是因为,当你设置clientOrders
你写
setClientOrders(dispatch(props.fetchClientOrders(props.clientId)))
dispatch 函数不会返回你想要的数据。如果要从 redux 存储中检索数据,则必须执行以下操作:
import { useSelector} from 'react-redux';
...
function ClientOrdersList(props) {
...
const data_you_stored_in_redux = useSelector(state => state.YourReducer.data_you_stored_in_redux); // this line out of useEffect
...
}
YourReducer
是包含data_you_stored_in_redux
您在 redux 存储中传递的 reducer 的名称,例如:
import { createStore, combineReducers } from "redux";
import YourReducer from '../../components/YourComponent/YourReducer';
...
const reducers = combineReducers({
YourReducer,
... //other reducers
});
const store = createStore(reducers);
推荐阅读
- python - 将python数据导出到elasticsearch
- jasper-reports - 我可以在 Jasper 报告中动态更改数据集吗?
- rest-assured - REST Assured:将字段与长值进行比较
- ionic3 - 如何在离子的背景状态下检查互联网连接
- git - Git:如何重新引入以前的删除或如何将父级合并到子级提交
- azure-devops - 如何从发布管道在 App Center 中的实际移动设备上运行 UITest
- c++ - 识别MSCV的单轴分区算法
- file - 如何在 Erlang 中使用通配符 * 检查文件是否存在?
- pdfbox - 如何使用 PDFBox java 识别和删除 PDF 中的隐藏文本
- javascript - 通过选择它从三个js场景中删除对象