state값을 직접변경하면 안되고 함수의 형태로 변경해야하는 이유는 뭘까?
this.setState에 값을 변경해줘야하는것. 그 이유는 React입장에서는 React 모르게 바꾼것이기 때문에 안되는 것이다.
this.state.mode = 'welcome';
이것을 아래와 같이 변경해야하며 그 함수가 내부적으로 많은일을 할 수 있게 해주는 것이 setState로 변경해줘야한다.
return (
<div className="APP">
{/* <Subject title = {this.state.Subject.title}
sub={this.state.Subject.sub}></Subject> */}
<header>
<h1><a href="/" onClick = {function(e){
console.log(e);
e.preventDefault();
this.setState({
mode: 'welcome'
});
}.bind(this)}>{this.state.Subject.title}</a></h1>
{this.state.Subject.sub}
</header>
헷갈리지말아야할것은 App이라고 하는 것의 최초로 실행되는 함수에서는 가능하다. 생성자 즉 constructor에서는 다음과 같이 해도 괜찮다.
class App extends Component {
constructor(props) {
super(props);
this.state = {
mode :'welcome',
Subject:{title:'WEB', sub:'World Wide Web!'},
welcome:{title:'Welcome', desc: 'Hello, React!!'},
Contents :[
{id :1, title:'HTML', desc:'HTML is for information'},
{id :2, title:'CSS', desc:'CSS is for design'},
{id :3, title:'JavaScript', desc:'JavaScript is for interactive'},
]
}
}
render() {
console.log('App render')
var _title, _desc = null;
if(this.state.mode === 'welcome'){
_title = this.state.welcome.title;
_desc = this.state.welcome.desc;
} else if (this.state.mode === 'read'){
_title = this.state.Contents[0].title;
_desc = this.state.Contents[0].desc;
}
return (
<div className="APP">
{/* <Subject title = {this.state.Subject.title}
sub={this.state.Subject.sub}></Subject> */}
<header>
<h1><a href="/" onClick = {function(e){
console.log(e);
e.preventDefault();
this.setState({
mode: 'welcome'
});
}.bind(this)}>{this.state.Subject.title}</a></h1>
{this.state.Subject.sub}
</header>
<TOC data = {this.state.Contents}></TOC>
<Content title = {_title} desc ={_desc}></Content>
</div>
);
}
}
export default App;