首页 > 解决方案 > 在 redux 中用新状态更新状态

问题描述

我想向我的 php 页面发出请求以检索数据,直到页面加载。我用 axios 提出了这个请求“这个请求是成功的”。我想更改存储中的状态“状态槽成功但更改为否”。我发现一个错误:TypeError:无法读取未定义的属性“props”,位于“componentDidMount 处理成功”级别。

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)

标签: javascriptreactjsreduxreact-redux

解决方案


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:无法读取未定义的属性“道具”


推荐阅读