javascript - react 官网 一个实例不是太懂
PHP中文网
PHP中文网 2017-04-11 09:41:14
[JavaScript讨论组]
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 (
      <p>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </p>
    );
  }
}

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}) => (
  <p>
    <Header addTodo={actions.addTodo} />
    <MainSection todos={todos} actions={actions} />
  </p>
)

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 里面返回了该属性?对这里有些疑问? 
})
PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
黄舟

每次render 都重新 声明一个新的isLoggedIn变量。这个变量的作用域也仅限于render函数体内。
一般render的时候 需要用state 或者props 中取出值来渲染。
正常情况下如果这个值不需要 发生重新赋值的话。
const 就是理想的选择。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号