React Redux .map 项目,并在<子组件中>获取要为每个项目显示的数据



我有带有客户端列表的Component>对于每个客户我将添加一个Child Component,其中包含客户订单的列表

Child Component,我调用fetchClientOrders(用于订单列表(,并将其发送到Parent Component中的道具-当我尝试在Child Component中调用setClientOrders时,我得到了一个错误"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是包含您在redux存储中传递的data_you_stored_in_redux的reducer的名称,如:

import { createStore, combineReducers } from "redux";
import YourReducer from '../../components/YourComponent/YourReducer';
...
const reducers = combineReducers({
YourReducer,
... //other reducers
});
const store = createStore(reducers);

最新更新