老师看看这个

来源:2-10 React 中的生命周期函数(3)

慕标5156652

2020-10-20 16:43:19

# 具体遇到的问题
点击数字不增加
# 报错信息的截图
http://img.mukewang.com/climg/5f8ea32009c51ba328680908.jpg# 相关课程内容截图

# 尝试过的解决思路和结果

# 粘贴全部相关代码,切记添加代码注释(请勿截图)

index.js

import React from 'react';

import ReactDom from 'react-dom';

import Counter from './counter';

import Number from "./number";

ReactDom.render(<div><Counter/><Number/></div>,document.getElementById("root"))

index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

<meta

name="description"

content="Web site created using create-react-app"

/>

<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<title>SKY React</title>

</head>

<body>

<noscript>You need to enable JavaScript to run this app.</noscript>

<div id="root"></div>

</body>

</html>


number.js

import React,{Component} from 'react';

class Number extends Component{

render() {

return <div>{this.props.count}</div>

}

}

export default Number;

counter.js

import React, { Component} from "react";

import Number from './number';

class Counter extends Component {

handleClick() {

const newNumber = this.state.number+1;

this.setState({

number: newNumber,

});

}

constructor(props) {

console.log("constructor");

super(props);

this.handleClick = this.handleClick.bind(this);

this.state = {

number: 1,

};

}

// 挂在前自动执行

componentWillMount() {

console.log("componentWillMount");

}

//   渲染时自动执行

// 组件更新前  componentWillMount之后 自动执行

render() {

console.log("render");


return (

<div>

<div onClick={this.handleClick}>hello world</div>

<Number count={this.state.number}/>

</div>);

}

//   挂载后     自动执行

componentDidMount() {

console.log("componentDidMount");

}

//组件更新前   自动执行

shouldComponentUpdate() {

console.log("shouldComponentUpdate");

return false;

}

//     //组件更新完执行 shouldComponentUpdate之后 自动执行

componentWillMount() {

console.log("componentWillMount");

}

//   组件更新前  render之后   自动执行

componentDidUpdate() {

console.log("componentDidUpdate");

}

//   组件从页面中移除前   自动执行

componentWillUnmount() {

console.log("componentWillUnmount");

}

}

export default Counter;



写回答

1回答

好帮手慕久久

2020-10-20

同学你好,由于counter组件的shouldComponentUpdate生命周期函数中,返回值写成了false,所以点击组件后,组件的数据无法更新,导致数字不更新。

需要做如下修改:

http://img.mukewang.com/climg/5f8eab77092a749205810156.jpg

http://img.mukewang.com/climg/5f8eab8009de9d8502740098.jpg

祝学习愉快!

0

0 学习 · 10739 问题

查看课程