如何在调用redux操作后立即更新组件中的道具?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (239)

基本上,我正在尝试实施一个解决方案,每当用户从食谱书更新食谱时,它应该将更新的食谱发送到我的数据库。但是,我注意到它“滞后”。例如,如果我更新配方,它只会在调用fetch到我的后端时发布先前的更新。

我发现这是因为mapStateToProps在每次更新后都会被调用。但是,我需要在执行操作后立即调用它,这样当我调用fetch到后端时,它会将正确的信息发布到数据库。我怎样才能做到这一点?

import React, { Component } from 'react'
import { connect } from 'react-redux' 
import { addGenre, addIngredient, addRecipe, addStep } from '../actions/index'
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import AddIcon from '@material-ui/icons/Add'; 

const mapStateToProps = (state) => {  // takes application state as argument
    return { articles: state.articles, username: state.username } // of type array of objects
} 

const mapDispatchToProps = dispatch => {
    return {
        addGenre: genre => dispatch(addGenre(genre)),
        addRecipe: recipe => dispatch(addRecipe(recipe)),
        addIngredient: ingredient => dispatch(addIngredient(ingredient)),
        addStep: step => dispatch(addStep(step))
    }
}


class Form extends Component { 
    constructor(props){
        super(props)
        this.state = {
            title: ''
        }
    }
    componentDidMount(){

    }
    componentWillReceiveProps(){

    } 
    async updateBook(){ 

        const data = {recipeBook: this.props.articles, username: this.props.username}
        console.log(data)
        const response = await fetch("/updatebook", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
        })  

        const body = await response.json()
        return body
    } 
    addToGenres(event){
        event.preventDefault()
        console.log("adding to genres supposedly")
        this.props.addGenre( this.state.title ) 
        console.log('genre new data is ')
        console.log(this.props.articles)

        this.updateBook().then( res => {
            console.log("book updated")
            this.setState({title: ''})

        }).catch( err => {
            console.log(err)
        }) 

    }

    addToRecipes(event){
        event.preventDefault() 
        this.props.addRecipe({genre:this.props.articles[this.props.genreIndex].genre,
            title: this.state.title})
        this.setState({title: ''}) 
    }

    addToIngredients(event){

        event.preventDefault() 
        this.props.addIngredient(
            {
                genre: this.props.genreIndex,
                recipe: this.props.articles[this.props.genreIndex].recipes[this.props.recipeIndex].title,
                ingredientTitle: this.state.title
            })
        this.setState({title: ''})
    }

    addToSteps(event){

        event.preventDefault()

        this.props.addStep(
            {
                genreIndex: this.props.genreIndex,
                recipeTitle: this.props.articles[this.props.genreIndex].recipes[this.props.recipeIndex].title,
                stepTitle: this.state.title
            }
        )

        this.setState({title: ''})

    }


    handleChange(event){
        this.setState({ title: event.target.value })
    }

    handleSubmit(event){ 
        if( this.props.formType === 'adding-to-genres' ){
            this.addToGenres( event )
        } else if ( this.props.formType === 'adding-to-recipes'){
            this.addToRecipes( event )
        } else if ( this.props.formType === 'adding-to-ingredients' ){
            this.addToIngredients( event )
        } else if ( this.props.formType === 'adding-to-steps' ){
            this.addToSteps(event)
        } else {
            alert('bug')
        }
    } 

    render(){
        const { title } = this.state 
        return (
            <form onSubmit={this.handleSubmit.bind(this)}>
                <div> 
                    <TextField
                    id="Add Item"
                    label="Add Item"
                    className='form-control'
                    value={title}
                    onChange={this.handleChange.bind(this)}
                    margin="normal"
                    />  
                    <Button size='small' variant="fab" color="primary" aria-label="add" type='submit'>
                        <AddIcon />
                    </Button>

                </div>
            </form>
        )
    } 
}

export default connect(mapStateToProps, mapDispatchToProps)(Form)
提问于
用户回答回答于

事实证明,对异步函数的调用updateBook()应该在React.Component函数下进行调用,该函数componentDidUpdate()在redux的connect函数之后调用。

扫码关注云+社区

领取腾讯云代金券