如何在redux工具箱中将参数传递给createAsyncThunk?

时间:2020-11-08 20:32:17

标签: javascript reactjs redux redux-toolkit

所以我是redux-toolkit的新手,我想做一些非常简单的事情。我想通过此辅助函数在POST请求上发送一些数据。所以我尝试了

this.myMatch = this.route.snapshot.paramMap.get("createdMatchIdKey");

this.golfDataService.GetSelectedMatch(this.myMatch)
  .subscribe(result => {
    this.match = result;
    this.setupTable(this.match.matchCourseId);
    this.golfDataService.GetSelectedGolfCourse(this.match.matchCourseId)
      .subscribe(result => {
        this.course = result;
        console.log(this.course);
      })
    this.golfDataService.GetSelectedCourseTees(this.match.matchCourseId)
      .pipe(takeUntil(this.onDestroy))
      .subscribe(result => {
        this.tees = result;
        console.log(this.tees);
        for (var i = 0; i < this.tees.length; i++) {
          this.golfDataService.GetHoles(this.tees[i].teeIdKey)
            .subscribe(result => {
              console.log(this.teeHoleInfo);
              this.teeHoleInfo.push(result);
              console.log(this.match);
            })
        }
      })
  })

但是当我这样称呼

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async ({ name, data }) => {
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

typescript抱怨说我的论点数不正确。那么我应该如何将args传递给此函数呢?或使用工具包执行此操作的方式是什么?

2 个答案:

答案 0 :(得分:1)

这是 React-Redux 在你使用 createAsyncThunk 时所说的

<块引用>

当你调度 thunk 时,你只能传递一个参数给它。如果需要传递多个值,请在单个对象中传递它们

所以代替

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async ({ name, data }) => { // here you have two arguments
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

你只能有一个参数:

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
    async (yourData) => {
        const {name, data} = yourData;
        return fetch('/payments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name,
                data,
            }),
        })
            .then((res) => res.json())
            .then((res) => res)
    },
)

thunk 调用中分解您的对象。

参考:here

答案 1 :(得分:0)

您实际上需要给这些参数指定类型:

export const submitPaymentToServer = createAsyncThunk(
    'data/fetchAll',
     async ({ name, data }: { name: string, data: MyDataType }) => {
        return fetch('/payments', {