class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
为什么这里 const isLoggedIn = this.state.isLoggedIn;
ES6 里面用const 声明的变量不是不能改变他的值,这里为什么通过状态可以改变,不是很懂??
补充问题, 学习redux遇到的问题 github地址 example/todoMVC
这个栗子里面的问题
App.js
import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Header from '../components/Header'
import MainSection from '../components/MainSection'
import * as TodoActions from '../actions'
const App = ({todos, actions}) => (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
)
App.propTypes = {
todos: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
}
const mapStateToProps = state => ({
todos: state.todos //=====================> 这里面的state.todos 是从哪里返回的???
})
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(TodoActions, dispatch)
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(App)
问题是
const mapStateToProps = state => ({
todos: state.todos //=====================> 这里面的state.todos 是从哪里返回的???
//reducer 返回的是没有 todos属性的, 只有combineReducer 里面返回了该属性?对这里有些疑问?
})
每次render 都重新 声明一个新的isLoggedIn变量。这个变量的作用域也仅限于render函数体内。
一般render的时候 需要用state 或者props 中取出值来渲染。
正常情况下如果这个值不需要 发生重新赋值的话。
const 就是理想的选择。