我正在学习使用react和redux,这让我有些困惑。
我要做什么:
reducers.js
const initialState = {
meetings: [],
idmeeting: []
}
export const reducer = (state = [] , action) => {
switch(action.type){
case 'MEETINGS_LIST':
return [...state, ...action.meetings];
case 'MEETING_CURRENT':
return [...action.idmeeting]
default:
return state;
}
}
export default reducer;
actions.js
export const meetingsList = (meetings) => {
return(dispatch) => {
fetch(`https://jsonplaceholder.typicode.com/users`, {
headers : {
'Accept': 'application/json'
}
})
.then(
res => res.json(),
error => console.log('An error occurred.', error))
.then(meetings => {
dispatch({
type: 'MEETINGS_LIST',
meetings: meetings
})
})
}
}
export const meetingSingle = (idmeeting) => {
// at the moment I use the information from the user 1
fetch(`https://jsonplaceholder.typicode.com/users/1`, {
headers : {
'Accept': 'application/json'
}
})
.then(
res => res.json(),
error => console.log('An error occurred.', error))
.then(idmeeting => {
dispatch({
type: 'MEETING_CURRENT',
idmeeting: idmeeting
})
})
}
MeetingList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { meetingsList, meetingSingle } from '../Redux/actions';
class MeetingsList extends Component {
constructor(props){
super(props);
this.state = {}
}
componentDidMount(){
this.props.meetingsList();
}
handleClick(id){
alert("ALERT " + id);
}
render(){
console.log(this.props.meetings)
const listMeetings = this.props.meetings.map((meeting) =>
<li key={meeting.id}>{meeting.name}
<button key={meeting.id} onClick={meetingSingle(meeting.id)} value={meeting.id}>{'Details'}</button>
</li>);
return(
<div>
<ul>{listMeetings}</ul>
</div>
)
}
}
function mapStateToProps(state){
return {meetings: state}
};
function mapDispatchToProps(dispatch){
return {
meetingsList: (meetings) => dispatch(meetingsList(meetings)),
meetingSingle: (idmeeting) => dispatch(meetingSingle(idmeeting))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MeetingsList)
所以我的问题是单击按钮并进行api调用以接收详细信息。谁能帮助我了解问题出在哪里(目前我收到错误消息,即未在操作中定义调度,但我认为这不是唯一的问题)
谢谢
答案 0 :(得分:0)
当组件将使用错误的数据渲染时,您的操作将调度。您需要向onClick提供功能,而不是在onClick内部执行
此
onClick={meetingSingle(meeting.id)}
应该是
onClick={() => meetingSingle(meeting.id)}
您需要将存储导入到actions.js文件中,然后在需要的地方使用store.dispatch()
import { store } from './your path for store';
export const meetingSingle = (idmeeting) => {
// at the moment I use the information from the user 1
fetch(`https://jsonplaceholder.typicode.com/users/1`, {
headers : {
'Accept': 'application/json'
}
})
.then(
res => res.json(),
error => console.log('An error occurred.', error))
.then(idmeeting => {
store.dispatch({
type: 'MEETING_CURRENT',
idmeeting: idmeeting
})
})
}