如何将状态传递给动作创建者

时间:2020-10-24 04:02:14

标签: javascript reactjs redux

我想知道如何将状态传递给操作,以便它可以使用状态进行API调用。我要传递的状态是输入,因为它是发送到Clarifai的服务器以预测名人的图像URL。句柄搜索负责将状态更新为URL。

我试图在没有运气的情况下使用获取状态

这是我的动作

export const requestPrediction = () => {
  return function (dispatch, getState) {
    dispatch(fetchCelebrequest)
    let input = getState().input 
    app.models.predict(Clarifai.CELEBRITY_MODEL,
      input)
      .then(res => {
        const data = res.outputs[0]['data']['regions'][0]['data'].concepts[0]
        dispatch(fetchCelebSuccess(data))
      })
      .catch(err => {
        const error = err.message
        dispatch(fetchCelebFailed(error))
      })
  }
}

这是我的reducer.js

import { 
    CHANGE_SEARCHFIELD,
    REQUEST_PREDICTION_PENDING,
    REQUEST_PREDICTION_SUCESS,
    REQUEST_PREDICTION_FAILED
} from './constants'


const initialState = {
    input: '',
    imageUrl: '',
    box: {},
    isSignedIn: false,
    isPending: false,
    celeb: {},
    error: '',
    celebConfidence: [],
    user: {
    id: '',
    name: '',
    email: '',
    entries: 0,
    joined: ''
    }
}

export const handleSearch = (state=initialState, action={}) => {
    switch (action.type) {
        case CHANGE_SEARCHFIELD:
            return { ...state, input: action.payload }
        default:
            return state
    }
}

export const requestPrediction = (state=initialState, action={}) => {
    switch(action.type) {
        case REQUEST_PREDICTION_PENDING:
            return {...state, isPending: true}
        case REQUEST_PREDICTION_SUCESS:
            return {...state, celebName: action.payload, isPending: false}
        case REQUEST_PREDICTION_FAILED:
            return {...state, error: action.payload, isPending: false}
        default:
            return state
    }
}

1 个答案:

答案 0 :(得分:1)

正确的方法是通过setState,因为更新是异步的。 您可以查看此链接。 How can I pass state to an action in React.js?