我正在学习使用react和redux。
所以我有一些问题:
我以这种方式构造:
reducers.js
const initialState = {
meetings: []
}
export const reducer = (state = initialState, action) => {
switch(action.type){
case 'MEETINGS_LIST':
return [...state.meetings, action.meetings];
default:
return state;
}
}
export default reducer;
action.js
export const meetingsList = (meeting) => {
return(dispatch) => {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(
res => res.json(),
error => console.log('An error occurred.', error))
.then(meetings => {
dispatch({
type: 'MEETINGS_LIST',
meetings: meetings
})
})
}
}
在actions.js中进行提取是正确的吗?还是我应该做减速器?
无论如何,我的问题在主页上,
class MeetingsList extends Component {
constructor(props){
super(props);
this.state = {}
}
componentDidMount(){
this.props.meetingsList();
}
render(){
console.log(this.props.meetings)
return(
<div>
</div>
)
}
}
function mapStateToProps(state){
return {meetings: state}
};
function mapDdispatchToProps(dispatch){
return {
meetingsList: (meetings) => dispatch(meetingsList(meetings))
}
}
export default connect(mapStateToProps, mapDdispatchToProps)(MeetingsList)
我想在屏幕上打印道具的内容。它是一个数组[10],我曾想过使用映射能够打印每个单独的数组,但是每次尝试时,它告诉我不可能使用未定义的映射。我该怎么办?
谢谢
几件事:
initialState
定义为对象。在MEETINGS_LIST
类型上,您将返回一个数组。MEETINGS_LIST
后,您将传播未定义的state.meetings
(因为状态不再是对象){ meetings: meetings }
,其中meetings
是一个数组(因为此时正在检索用户列表)。但是您没有在MEETINGS_LIST
处理程序中散布该数组。所以:
(state = initialState)
更改为(state = [])
。return [...state, ...action.meetings];
const elements = this.props.meetings.map((meeting) => <li key={meeting.id}>{meeting.title}</li>);
return <ul>{elements}</ul>