【问题标题】:How do I update the props from a component immediately after calling a redux action?如何在调用 redux 操作后立即更新组件中的 props?
【发布时间】:2018-12-30 01:41:37
【问题描述】:

基本上,我正在尝试实施一种解决方案,每次用户从食谱书中更新食谱时,它都应该将更新后的食谱发送到我的数据库。但是,我注意到它“滞后”。例如,如果我更新一个食谱,它只会在调用 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)

【问题讨论】:

  • 你能发布你的整个组件吗?

标签: reactjs react-redux


【解决方案1】:

事实证明,对 async 函数 updateBook() 的调用应该在名为 componentDidUpdate() 的 React.Component 函数下,该函数在 redux 的 connect 函数之后调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2020-08-10
    • 2019-11-15
    • 2017-05-06
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多