简体   繁体   English

在 redux 中用新的 state 更新 state

[英]updating state with new state in redux

i want to make a request to my php page to retrieve data until the page is loaded.我想向我的 php 页面发出请求以检索数据,直到页面加载。 i made this request with axios' this request is successful ". i want to change state in store "the state tank is successful but the change is no". I found an error: TypeError: Cannot read property 'props' of undefined, at 'componentDidMount handle succes' level.我用 axios 发出了这个请求“这个请求是成功的”。我想在商店中更改 state “state 坦克成功,但更改为否”。我发现一个错误: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)

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
        });
    }

See This.见这个。

React - TypeError: Cannot read property 'props' of undefined React - TypeError:无法读取未定义的属性“道具”

Try using an arrow function instead for the axios callback to preserve e context of this :尝试使用箭头 function 代替 axios 回调以保留this上下文:

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

Hopefully that helps!希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM