首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在调用redux操作后立即更新组件中的道具?

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

Stack Overflow用户
提问于 2018-07-22 19:31:14
回答 1查看 36关注 0票数 0

基本上,我正在尝试实现一个解决方案,每次用户更新食谱时,都应该将更新后的食谱发送到我的数据库中。然而,我注意到它“滞后”。例如,如果我更新了一个配方,它只会在调用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)
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51464645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档