首页 > 解决方案 > 如果动作成功需要添加回调函数。它不工作(反应原生和redux)

问题描述

我已经使用 axios 将数组数据上传到服务器。但是在上传完成后(即如果成功),我想清空一个数组或向数组中添加一些元素。Everthing 可以工作,但是在它成功后我该如何对数组进行操作,它在以下代码中不起作用。谢谢你。

代码:

var testArray = [];

uploadData = () => {
    this.props.uploadataToServer(testArray);

    if (this.props.uploadStatus == true) { //this code is not working
        testArray = [];
    }
}

render() {
    return(
        <View>
            <TouchableOpacity onPress={() => this.uploadData()}>
                <Text>Upload data</Text>
            </TouchableOpacity>
        </View>
    )
}

const mapStateToProps = (state) => {
    const { uploadStatus } = state.Upload;
    return { uploadStatus };
}

行动:

export const uploadataToServer = (testArray) => {
    return (dispatch) => {
        axios({
            url: testUrl,
            data: {
                upladArray: testArray
            }
        }).then(response => {
            if(response.data.status == true) {
                dispatch({
                    type: UPLOAD_TO_SERVER,
                    dataStatus: response.data.status,
                })
            }
        })
    }
}

减速器:

switch(actions) {
    case UPLOAD_TO_SERVER:
        return { uploadStatus: actions.dataStatus}
}

标签: react-nativereduxreact-redux

解决方案


您需要签入componentDidUpdate,因为届时您将收到更新的道具

componentDidUpdate(prevProps) {
  if (prevProps.uploadStatus !== this.props.uploadStatus) {
    if (this.props.uploadStatus == true) {
        testArray = [];
    }
  }
}

推荐阅读