老师,shouldComponentUpdate返回false,为什么在父组件Input输入值的时候,item也被刷新了?
来源:4-9 React 生命周期函数的使用场景
榎目贵音
2020-02-07
为什么和老师的视频结果不一样呢?
我的代码是直接拷贝过来的
import React, { Component, Fragment } from "react";
import TodoItem from "./TodoItem";
import axios from "axios";
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: "",
list: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleItemDelete = this.handleItemDelete.bind(this);
}
render() {
return (
<Fragment>
<div>
<label htmlFor="insertArea">输入内容</label>
<input
id="insertArea"
className="input"
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
<button onClick={this.handleBtnClick}>提交</button>
</div>
<ul>{this.getTodoItem()}</ul>
</Fragment>
);
}
componentDidMount() {
axios
.get("/api/todolist")
.then(() => {
alert("succ");
})
.catch(() => {
alert("error");
});
}
getTodoItem() {
return this.state.list.map((item, index) => {
return (
<TodoItem
key={item}
content={item}
index={index}
deleteItem={this.handleItemDelete}
/>
);
});
}
handleInputChange(e) {
const value = e.target.value;
this.setState(() => ({
inputValue: value
}));
}
handleBtnClick() {
this.setState(prevState => ({
list: [...prevState.list, prevState.inputValue],
inputValue: ""
}));
}
handleItemDelete(index) {
this.setState(prevState => {
const list = [...prevState.list];
list.splice(index, 1);
return { list };
});
}
}
export default TodoList;
todoItem
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class TodoItem extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return false;
}
render() {
const { content } = this.props;
return (
<div onClick={this.handleClick}>
{content}
</div>
)
}
handleClick() {
const { deleteItem, index } = this.props;
deleteItem(index);
}
}
TodoItem.propTypes = {
content: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
deleteItem: PropTypes.func,
index: PropTypes.number
}
export default TodoItem;
截图:
工具设置:
写回答
1回答
-
Dell
2020-02-11
你这也没变啊,上面ggg,下面是个f
022020-02-13
相似问题