React-Redux:可视化元素数组

问题描述 投票:0回答:1

我正在学习使用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],我曾想过使用映射能够打印每个单独的数组,但是每次尝试时,它告诉我不可能使用未定义的映射。我该怎么办?

谢谢

reactjs redux
1个回答
1
投票

几件事:

  1. 您正在将initialState定义为对象。在MEETINGS_LIST类型上,您将返回一个数组。
  2. [第二次发送MEETINGS_LIST后,您将传播未定义的state.meetings(因为状态不再是对象)
  3. 您正在调度{ meetings: meetings },其中meetings是一个数组(因为此时正在检索用户列表)。但是您没有在MEETINGS_LIST处理程序中散布该数组。

所以:

  1. (state = initialState)更改为(state = [])
  2. 将您的“ MEETINGS_LIST”处理程序更改为return [...state, ...action.meetings];
  3. 现在您可以循环会议:
const elements = this.props.meetings.map((meeting) => <li key={meeting.id}>{meeting.title}</li>);

return <ul>{elements}</ul>
© www.soinside.com 2019 - 2024. All rights reserved.