【问题标题】:How to render new data (or GET new) after making a POST request with axios?使用 axios 发出 POST 请求后如何渲染新数据(或 GET new)?
【发布时间】:2022-06-12 22:48:50
【问题描述】:

我正在使用 mockapi.io 练习 Axios API 调用

在我发出一个创建新数据的 POST 请求后,我想用更新后的数据呈现 FlatList。我正在考虑发出一个新的 GET 请求来执行此操作,但我没有成功。

我需要帮助

这里我调用GET请求,已经有mock数据,使用FlatList查看

ListScreen.js

class ListScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }
    }
    componentDidMount() {
        axios.get('insert url')
            .then(res => {
                this.setState({
                    data: res && res.data ? res.data : []
                })
            })
            .catch(err => {
                console.log('Run into problem')
            })
    }
    render() {
        const { data } = this.state;
        return (
            <View>
                <FlatList
                    data={data}
                    renderItem={({ item }) => {
                        return (
                            <Item
                                name={item.lastName}
                                phone={item.phoneNumber}
                            />
                        );
                    }}
                    keyExtractor={(item) => item.id}
                />
            </View>

这里是我调用 POST 请求的地方

class Create extends Component {

    handleSubmitData = (value) => {
        console.log('check value: ', value)
        axios.post('insert url', {
            lastName: `${value.Name}`,
            phoneNumber: `${value.Phone}`,
        })
            .then((response) => {
                console.log('here is what you upload: ', response.data)
            })
            .catch((err) => {
                console.log('Run into problem')
            })
    }
    render() {
        return (
            <CreateForm
                handleSubmitData={this.handleSubmitData}
            />
        )
    }
}

CreateForm 组件看起来像这样

class CreateForm extends Component {
    render() {
        const { handleSubmit } = this.props;
        return (
            <View>
                <View>
                    <Field
                        name="Name"
                        component={}
                    />
                    <Field
                        name="Phone"
                        component={}
                    />
                </View>
                <View>
                    <Button
                        title='Save'
                        onPress={handleSubmit(this.props.handleSubmitData)}
                    />
                </View>
            </View>
        )

【问题讨论】:

    标签: javascript reactjs react-native axios


    【解决方案1】:

    这可以通过将状态从 ListScreen 提升到 ListScreen 的父级来完成。

    在 ListScreen 中,取出状态并移入其父级:

        this.state = {
            data: [],
        }
    

    将状态作为道具传递给 ListScreen,同时传递 fetch 函数(见下文):

    <ListScreen data={this.state.data} fetchListData={this.fetchListData} />
    

    更改 ListScreen 的渲染函数以从 props 访问数据:

    const { data } = this.props;
    

    axios.get() 移出 ListScreen 并移到父组件上的方法中。

    class App extends Component {
        fetchListData() {
            axios.get('insert url')
                .then(res => {
                    this.setState({
                        data: res && res.data ? res.data : []
                    })
                })
                .catch(err => {
                    console.log('Run into problem')
                })
        }
    }
    

    在ListScreen中,调用componentDidMount中的函数:

    componentDidMount() {
        this.props.fetchListData();
    }
    

    或者,您可以在父组件的componentDidMount() 中调用它。例如,如果您呈现多个 ListScreen,这可能是首选。

    最后,在 Create 组件中,传递 fetch 函数:

    <Create fetchListData={this.fetchListData} />
    

    成功创建时调用它:

            .then((response) => {
                this.props.fetchListData();
                console.log('here is what you upload: ', response.data)
            })
    

    【讨论】:

    • 我可以看到这个想法。但是我有点困惑在哪里渲染 Create 组件以传递 fetch 函数。
    • Create 组件应保留在其现有位置。您可能需要根据 ListScreen 上方的内容进行相应更改。
    【解决方案2】:

    正如我在您的代码中看到的,当您发出 POST 请求时,它不会在您的屏幕上显示更新的数据,因为成功结果时没有 GET 请求回调。

    建议您没有使用 redux ,在ListScreen.js 中,您可以将 GET 请求包装到一个函数中并在componentDidMount() 中调用它。它应该是这样的:

    const getData () => {
        axios.get('insert url')
                .then(res => {
                    this.setState({
                        data: res && res.data ? res.data : []
                    })
                })
                .catch(err => {
                    console.log('Run into problem')
                })
    }
    
    
    componentDidMount() {
        this.getData()
    }
    

    因此,您需要将 GET 请求函数作为道具传递或钻取到您的子组件中,并在 POST 请求回调中使用它。最终的 POST 请求方法应如下所示:

    handleSubmitData = (value) => {
            console.log('check value: ', value)
            axios.post('insert url', {
                lastName: `${value.Name}`,
                phoneNumber: `${value.Phone}`,
            })
                .then((response) => {
                    console.log('here is what you upload: ', response.data)
                    getData()
                })
                .catch((err) => {
                    console.log('Run into problem')
                })
        }
    

    如您所见,在您的 POST 请求完成后,它会触发一个 GET 请求来更新您的父状态,从而产生一个包含更新数据的屏幕。但是,您必须确保根据组件结构正确传递参数。

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 2022-01-23
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多