0

我很难理解如何将参数放入 axios.post 请求中?到目前为止,关于我的应用程序的一些信息:

我有一个正在与 RethinkDB 实例对话的快速应用程序。我还有一个独立的 React/Redux 应用程序。我可以在我的动作创建者中成功地点击我的快速端点,axios.get并在 React 组件中显示该数据(用户)。但是,现在我正在尝试将参数发送到我的快递应用程序中的另一条路线,并让它将该用户保存在 rethinkdb 数据库中。我暂时不关心身份验证。我在 express 端正确设置了它,并且可以通过 curl 从 express 应用程序中将虚拟用户保存到数据库,但我不知道如何通过 react app/react 表单的请求发送所需的参数。请在下面找到一些相关代码。

从我的 Express App API 中,当手动点击成功时,它将测试用户保存到数据库中。

var TestUser = thinky.createModel("TestUser", {
  id: String,
  name: String,
  email: String,
})

router.get('/newUser', (req, res) => {
  TestUser.save({
    name: 'sawyer',
    email: 'sawyer@test.com'
  }).then((result) => {
    console.log('Saved!')
    res.send(result)
  })
})

..以下是我的操作文件中单独的代码片段React and Redux App。老实说,我不确定要编写它并包含该user对象。

function addUser (user) {
  return {
    type: ADD_USER,
    user,
  }
}

export function addAndSaveUser (user) {
  return function (dispatch) {
    return dispatch(addUser(user)).then({
      axios.post("http://localhost:3000/users/newUser", )
    })
  }
}

任何帮助将不胜感激。

4

2 回答 2

1

只需将user对象作为第二个参数传递

axios.post("http://localhost:3000/users/newUser", user)

并且最好addUser在成功创建动作后调度它。

export function addAndSaveUser (user) {
  return function(dispatch) {
    axios.post("http://localhost:3000/users/newUser", user).then(res => {
      dispatch(addUser(res.data));
    });
  };
}
于 2016-08-17T09:03:24.437 回答
0

redux-thunk 能够使用withExtraArgument方法添加额外的参数,

import axios from 'axios'
import {combineReducers, createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import listTodoReducer from './components/ListTodo/ListTodo.reducer'

const API_ENDPOINT = "https://api...."

//combine project reducers
const reducers = combineReducers({
listTodoReducer
});

const api = axios.create({
headers:{
    authorization: 'TOKEN'
},
baseURL: `${API_ENDPOINT}/`
})

const store = createStore(
reducers,
applyMiddleware(thunk.withExtraArgument(api)) <------ LOOK
);

export default store

你可以在这里阅读更多关于Axios 作为 redux-thunk 的额外参数

于 2020-04-19T11:15:24.697 回答