【问题标题】:updating state with new state in redux在 redux 中用新状态更新状态
【发布时间】:2021-01-03 21:37:03
【问题描述】:

我想向我的 php 页面发出请求以检索数据,直到页面加载。我用 axios 提出了这个请求“这个请求是成功的”。我想改变商店中的状态“状态坦克是成功的,但改变是没有”。 我发现一个错误:TypeError: Cannot read property 'props' of undefined, at 'componentDidMount handle succes' level。

the code of the error page:
import React from "react";
import Axios from 'axios';
import {connect} from 'react-redux';
const mapDispatchtoprops=(dispatch)=>{
    return{
        load_state:(store)=>dispatch({type:"load_produit_to_state",payload:store})
    }
}
const mapStateToProps =(state)=>{
    return{
        state,
    }
};
class Produit extends React.Component{
      componentDidMount(){
        let request = new FormData;
        request.append("getters_produit","true");
        Axios.post('http://localhost/e_commerce/src/php/get.php',request).then(function(reponce){
            //handle succes
                this.props.load_state(reponce.data.liste_produit);
        }).catch(function(error){
            alert(error);
        }).then(function(){
            //always executed
        });
    }
render(){
    return(<div className="les_produit">
        { console.log( this.props.state), console.log( "from props")}
    </div>)}
}

store page:
import {createStore} from 'redux';
const reducer =(state,action)=>{
    switch(action.type){
       case 'load_produit_to_state':alert(action.payload); return{ liste_produit: action.payload };
        default: return state;
    }
}
const initialstate = {
    liste_produit:"none",
    profile:"nono"
}
export default createStore(reducer,initialstate)

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:
    componentDidMount(){
            const {load_state} = this.props // You Need This
            let request = new FormData;
            request.append("getters_produit","true");
            Axios.post('http://localhost/e_commerce/src/php/get.php',request).then(function(reponce){
                //handle succes
                    load_state(reponce.data.liste_produit);
            }).catch(function(error){
                alert(error);
            }).then(function(){
                //always executed
            });
        }
    

    看这个。

    React - TypeError: Cannot read property 'props' of undefined

    【讨论】:

      【解决方案2】:

      尝试使用箭头函数代替 axios 回调以保留 this 的上下文:

      Axios.post('http://localhost/e_commerce/src/php/get.php',request).then((reponce) =>
      

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 2019-01-19
        • 1970-01-01
        • 2018-02-11
        • 2019-07-28
        • 2019-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多