关于react.js:react使用state和总结一

react应用stat总结

1.开发环境 react.js
2.电脑系统 windows10专业版
3.在应用React开发的过程中,咱们要应用state,相当于vue中的data,上面我来分享一下 state的应用和总结,如果总结的不好请勿喷,心愿对你有所帮忙!
4.在 constructor中增加如下代码:

this.state = {
            resObj:null,
        }

5.在 reder(){}同级 定义一个函数:

 // 页面已加载 就申请数据
    chenget() {
        console.log("我是state的数据");
        console.log(store.getState());
        console.log("我是state的数据完结啦");
        chenecharts().then((res) => {
            chenres = res;
            this.getres(res);  //通过函数传参的形式
            console.log(res);
        })
        return re;
    }

6.定义存储 函数:

getres(chenrespro){
        console.log(chenrespro);
        this.setState({resObj:chenrespro},()=>{
            console.log(this.state.resObj);
        })
    }

–成果如下:

7.整体代码代码如下:

import React from "react";
import axios from 'axios'
import { chenecharts } from '@/api/home'
let chenres = undefined;
export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            xiaoxi: "会太累",
            chneresObj: undefined,
            resObj:null,
        }

        // 这个bind办法是必须的,以确保`this`能够在回调函数handleClick中应用
        this.chenget = this.chenget.bind(this);
    }

    render() {
        //用一个变量,承受
        const ChenHome =
            <div>
                <p> 我是home </p>
                <p> 我要坏加 </p>
                <a href="#/about" > 去about </a>
                <p>会哦加</p>
            </div>
        //完结啦
        return (ChenHome
        )
            ;
    }

    // 页面已加载 就申请数据
    chenget() {
        console.log("我是state的数据");
        console.log(store.getState());
        console.log("我是state的数据完结啦");
        let re = 123;
        chenecharts().then((res) => {
            chenres = res;
            this.getres(res);
            console.log(res);
            re = res;
            this.setState({ chneresObj: res }, () => {
                console.log(this.state.chneresObj);
                //留神:如果不加这个回调函数是看不到 批改的后果
            })
        })
        return re;
    }
    getres(chenrespro){
        // console.log(chenrespro);
        this.setState({resObj:chenrespro},()=>{
            console.log("+++++++++++");
            console.log(this.state.resObj);
            console.log("------------");
        })
    }

    componentWillMount() {
    }

    componentDidMount() {
        // 页面已加载 就申请数据
        this.chenget();

        let chnere = this.chenget();
        console.log(chnere);
    }
}

8.getres() 函数的作用就是存储后盾的数据,哪里须要在哪里调用。
9.本期的教程到了这里就完结啦,心愿对你有所帮忙,让咱们一起致力走向巅峰!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理