我是一名正在研究redux的初学者。我使用immutablejs将对象类型数据添加到状态。当您按下react组件上的按钮时,测试数据(Map ()
)将被推送到List()
。但有一个问题。按下按钮时,将输入以下类型的数据;当刷新页面时,将使用普通数据进行更新。为什么会这样?我非常感谢你的帮助。
import { handleActions } from 'redux-actions'
import axios from 'axios'
import { Map, List } from 'immutable'
let token = localStorage.token
if (!token)
token = localStorage.token = Math.random().toString(36).substr(-8)
let instance = axios.create({
baseURL: 'http://localhost:5001',
timeout: 1000,
headers: {'Authorization': token}
})
const GET_POST_PENDING = 'GET_POST_PENDING'
const GET_ALL_POST_SUCCESS = 'GET_ALL_POST_SUCCESS'
const CREATE_POST_SUCCESS = 'CREATE_POST_SUCCESS'
const GET_POST_FAILURE = 'GET_POST_FAILURE'
//actions
export const getPost = (postId) => dispatch => {
dispatch({type: GET_POST_PENDING});
return instance.get('/posts').then(
response => {
dispatch({
type: GET_ALL_POST_SUCCESS,
payload: response
})
}
).catch((error) => {
dispatch({
type: GET_POST_FAILURE,
payload: error
})
})
}
export const createPost = () => dispatch => {
dispatch({type: GET_POST_PENDING})
return instance.post('/posts',{
id: Math.random().toString(36).substr(-10),
timestamp: Date.now(),
title: 'test title',
body: 'test body',
category: 'redux',
author: 'minwoo',
deleted: false,
voteScore: 1
}).then(
response => {
console.log(response) //check data
dispatch({
type:CREATE_POST_SUCCESS,
payload: response
})
}
).catch((error) => {
dispatch({
type: GET_POST_FAILURE,
payload: error
})
})
}
const initialState = Map({
posts: List([]),
comments: List([])
})
我知道控制台不应该在这里。但是,当我按下按钮时,我想检查响应数据是否正确传输。
//reducer
export default handleActions({
[GET_POST_PENDING]: (state, action) => {
return state;
},
[GET_ALL_POST_SUCCESS]: (state, action) => {
console.log(action.payload.data)//for check data
return state.set('posts', List([...action.payload.data]))
},
[CREATE_POST_SUCCESS]: (state, action) => {
const posts = state.get('posts')
return state.set('posts', posts.push(
Map(action.payload.date)
))
},
[GET_POST_FAILURE]: (state, action) => {
return state
}
}, initialState)
以下代码是上面提到的React组件。
import React from 'react';
import PropTypes from 'prop-types'
import { List } from 'immutable';
const PostList = ({posts, PostActions: {getPost}}) => {
const postList = posts.map((post,i) => (
<div key={i}>
{post.title}
<button>edit</button>
<button>delete</button>
</div>
))
return (
<div className="PostList">
{postList}
</div>
)
}
PostList.proptypes = {
posts: PropTypes.instanceOf(List),
getPost: PropTypes.func
}
PostList.defaultProps = {
posts:[],
getPost: () => console.log('getPost is not defined')
}
export default PostList
答案 0 :(得分:0)
List
没有深度转换您的数据,因此当您将对象数组传递给List
时,您将获得一个包含普通JS对象的List
对象。
在fromJS
List
代替GET_ALL_POST_SUCCESS