如何在Redux中更新状态为阵列的单个文件?

时间:2019-06-08 09:09:28

标签: redux

我需要在状态=>图书=>(一本指定的图书)=>(一本图书字段)中更新一个字段。

我尝试这样做

export default function(state = initialState, action){
case EDIT_BOOK:
            return {
                ...state,
                books :{
                    ...state.books,
                    title: action.title
                }
            }

我的状态看起来像

books:[
  {
    "_id": "5cfa9698361a8427b85dc79f",
    "title": "Krzyżacy",
    "author": "Henryk Sienkiewicz",
    "__v": 0,
    "state": "toReads"
  },
  {
    "_id": "5cfa9bd1cb5c152ee4269a28",
    "title": "Quo Vadis",
    "author": "Henryk Sienkiewicz",
    "state": "toReads",
    "__v": 0
  }
]

//Action

export const editBook = (id, title) => dispatch => {
   axios
        .put(`http://localhost:5000/books/${id}`, title)
        .then(res => dispatch({
            type: EDIT_BOOK,
            payload: id,
            newTitle: title
        }))

因此,我的第二个问题

Access to XMLHttpRequest at 'http://localhost:5000/books/5cfa9698361a8427b85dc79f' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1 个答案:

答案 0 :(得分:0)

您错误地更新了阵列。请参阅redux文档中的以下模式: https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-an-item-in-an-array

请注意,不要将您的书籍从数组更改为对象(使用上面链接中的updateObjectInArray函数的输出并将其放入books属性)

case EDIT_BOOK:
    return {
        ...state,
        // here you are putting object instead of array into books
        books :{
            ...state.books,
            title: action.title
        }
    }

第二个问题的解决方案是使用您本地开发环境中的nginx,用于将请求传递到前端应用程序,并将后端api传递到正确的地址/端口。 Nginx配置看起来像这样(简化,只是为了提供正确的方向):

server {
   # port where nginx will run (you will debug your web application on this port from now)
    listen       8081;

    location / {
       # address of your frontend application (e.g. webpack dev server)
       proxy_pass http://127.0.0.1:3000;
    }
    location /backend {
       # address of your backennd application
       proxy_pass http://127.0.0.1:5000;
    }
}

如上所述,在配置之后,您需要在nginx代理而不是前端服务器(例如webpack dev服务器)上调试应用程序,但是服务器应仍在运行。根据上述配置,nginx代理应用程序的URL为:http://localhost:8081 每当您的应用程序想要调用后端api时,它都会通过以下方式进行操作:

// your old address will change into ...
http://localhost:5000/books/${id}

// ... this new address
/backend/books/${id}