Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在redux中使用API调用操作?_Reactjs_Redux_Redux Thunk - Fatal编程技术网

Reactjs 如何在redux中使用API调用操作?

Reactjs 如何在redux中使用API调用操作?,reactjs,redux,redux-thunk,Reactjs,Redux,Redux Thunk,我是redux新手,我正在尝试让它与我的应用程序一起工作,但我在理解如何在其中使用异步操作方面遇到了问题。我的动作就是api调用。只要我的其他状态不是空的,就应该调用此操作。我没有收到任何错误,但不认为调用了我的操作,因为数据是空的。谁能帮助我理解我做错了什么 这是我的actions.js。wordsFetchData是我需要调用的操作: export function wordsFetchDataSuccess(items){ return{ type: 'WORDS

我是redux新手,我正在尝试让它与我的应用程序一起工作,但我在理解如何在其中使用异步操作方面遇到了问题。我的动作就是api调用。只要我的其他状态不是空的,就应该调用此操作。我没有收到任何错误,但不认为调用了我的操作,因为数据是空的。谁能帮助我理解我做错了什么

这是我的actions.js。wordsFetchData是我需要调用的操作:

 export function wordsFetchDataSuccess(items){
    return{
        type: 'WORDS_FETCH_DATA_SUCCESS',
        items
    };
 }

 export function wordsAreFetching(bool){
     return{
        type: 'WORDS_ARE_FETCHING',
        areFetching: bool
     }
 }

 export function wordsHasErrored(bool) {
     return {
        type: 'WORDS_HAS_ERRORED',
        hasErrored: bool
     };
 }

 export function wordsFetchData(parsed) {
    return (dispatch) => {
        dispatch(wordsAreFetching(true));

        fetch('URL', {
            method: "POST",
            headers: {
                "Content-type": "application/json"
            },body: JSON.stringify({
                 words: parsed
        })
    })
        .then((response) => {
            if (!response.ok) {
                throw Error(response.statusText);
            }

            dispatch(wordsAreFetching(false));

            return response;
        })
        .then((response) => response.json())
        .then((items) => dispatch(wordsFetchDataSuccess(items)))
        .catch(() => dispatch(wordsHasErrored(true)));
    };
 }
以下是我的减速机:

export function word(state = [], action) {
switch (action.type) {
    case 'WORDS_FETCH_DATA_SUCCESS':
        return action.items;

    default:
        return state;
    }
}

export function wordsAreFetching(state = false, action) {
    switch (action.type) {
        case 'WORDS_ARE_FETCHING':
            return action.areFetching;

        default:
            return state;
    }
}

export function wordsFetchHasErrored(state = false, action) {
    switch (action.type) {
        case 'WORDS_HAS_ERRORED':
           return action.hasErrored;

    default:
        return state;

    }

 }
这是我的componentDidMount函数:

componentDidMount = (state) => {
    this.props.fetchData(state);
};
这是终止后应调用操作的函数:

 parseInput = async () => {
    console.log(this.state.textInput);
    let tempArray = this.state.textInput.split(" "); // `convert 
    string into array`
    let newArray = tempArray.filter(word => word.endsWith("*"));
    let filterArray  = newArray.map(word => word.replace('*', ''));
    await this.setState({filterArray: filterArray});
    await this.props.updateData(this.state.filterArray);
    if (this.state.projectID === "" && this.state.entity === "")
        this.dialog.current.handleClickOpen();
    else
        if (this.state.filterArray.length !== 0)
            this.componentDidMount(this.state.filterArray);
    };
这些是MapStateTops和mapDispatchToProps函数

const mapStateToProps = (state) => {
    return {
        items: state.items,
        hasErrored: state.wordsFetchHasErrored,
        areFetching: state.wordsAreFetching
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        fetchData: wordsFetchData
    };
};

执行抓取只需一个操作(即
WORDS\u正在抓取
),其余情况(即
WORDS\u已出错
WORDS\u抓取数据成功
)可以在减速机内处理

你的行动:

 export function wordsAreFetching(){
     return{
        type: 'WORDS_ARE_FETCHING',
     }
 }
您的新减速机:

export function word(state = [], action) {
switch (action.type) {
    case 'WORDS_ARE_FETCHING':
        return {...state, error: false, areFetching: true};
    case 'WORDS_FETCH_DATA_SUCCESS':
        return {...state, items: action.payload , areFetching: false};
    case 'WORDS_HAS_ERRORED':
        return {...state, error: true, areFetching: false};
    default:
        return state;
}

从此处获取数据后,您可以触发
WORDS\u FETCH\u DATA\u SUCCESS

export function wordsFetchData() {
    try {
        const response = await axios.get(YOUR_URL);
        return dispatch({ type: WORDS_FETCH_DATA_SUCCESS, payload: response.data });
    } catch (err) {
        return dispatch({ type: WORDS_HAS_ERRORED });
    }
 }
看看这个,它使用的axios可以帮助您进行异步调用。

以下几点:

  • 无需将状态传递到您的
    组件didmount
    ,您的
    mapDispatchToProps
    未使用它

  • 以下是构建这些功能的建议。它们更简洁易读

  • 其他注意事项和有用的东西: 如果您使用的是thunk,那么作为第二个参数,您可以访问这里的整个redux存储。例如:

        return (dispatch, getState) => {
            dispatch(wordsAreFetching(true));
            console.log('getState', getState());
           const { words } = getState().items;
    // This is a great place to do some checks to see if you _need_ to fetch any data!
    // Maybe you already have it in your state?
    
         if (!words.length) {
            fetch('URL', {
                method: "POST",
                headers: {
                    ......
          }
    
        })
    

    我希望这能有所帮助,如果您还需要什么,请随时询问。

    您使用过redux thunk或redux saga之类的中间件吗?是的,redux-thunk@RajSaraogi我想问题在于我说的不对
        return (dispatch, getState) => {
            dispatch(wordsAreFetching(true));
            console.log('getState', getState());
           const { words } = getState().items;
    // This is a great place to do some checks to see if you _need_ to fetch any data!
    // Maybe you already have it in your state?
    
         if (!words.length) {
            fetch('URL', {
                method: "POST",
                headers: {
                    ......
          }
    
        })