react 001

作者: 栗子daisy | 来源:发表于2019-08-07 11:10 被阅读0次

https://github.com/daisylys/react-0807

脚手架

create-react-app reactName //react-0807
npm start

路由

yarn add react-router-dom

//app.js
import React from "react";
import "./App.css";
import { HashRouter, Switch, Redirect, Route, Link } from "react-router-dom";
import Home from "./views/Home";
import About from "./views/About";
import Login from "./views/Login";
const routerMap = [
  { path: "/", name: Home, component: Home },
  { path: "/login", name: Login, component: Login },
  { path: "/about", name: About, component: About, auth: true }
];
function App() {
  const token = false;
  return (
    <div className="App">
      <HashRouter>
        <nav>
          <Link to="/">home</Link>
          <Link to="/about">About</Link>
        </nav>
        <Switch>
          {/* <Route path="/" component={Home} />
          <Route path="/about" component={About} /> */}
          {routerMap.map((item, index) => {
            return (
              <Route
                key={index}
                path={item.path}
                exact
                render={v =>
                  !item.auth ? (
                    <item.component {...v} />
                  ) : token ? (
                    <item.component {...v} />
                  ) : (
                    <Redirect
                      to={{
                        pathname: "/login",
                        state: { from: v.location }
                      }}
                    />
                  )
                }
              />
            );
          })}
        </Switch>
      </HashRouter>
    </div>
  );
}

export default App;

yarn add redux react-redux
yarn add redux-thunk redux-logger

redux/store

//index.js
import { createStore, applyMiddleware } from "redux";
import reducer from "../reducer/index";
import thunk from "redux-thunk";
import logger from 'redux-logger';
let store = createStore(reducer, applyMiddleware(logger,thunk));
console.log("store", store.getState());
export default store;
//initState.js
export default {
    videoHome: [],
    videoData: [],
    token: ''//登陆状态
  };
  

redux/reducer

//index.js
import { combineReducers } from "redux";
// import videoReducer from "./videoReducer";
import loginReducer from "./loginReducer";
const reducer = combineReducers({
  token: loginReducer,
//   videoData: videoReducer
});
export default reducer;

//loginReducer.js
import { LOG_IN } from "../actions/actionTypes";
import initState from "../store/initState";
 
export default (state = initState.token, action) => {
  switch (action.type) {
    case LOG_IN:
      return action.payload;
    default:
      return state;
  }
};

redux/action

//login.js
import { LOG_IN } from "./actionTypes";
export const changeActive = token => {
  return {
    type: LOG_IN,
    payload: token
  };
};

//actionTypes.js
const LOG_IN = "LOG_IN";
export { LOG_IN };

  • 使用
//login.js
import React, { Component } from "react";
import { connect } from "react-redux";
import { changeActive } from "../../redux/actions/login";
class Login extends Component {
  login = () => {
    let RedirectUrl = this.props.location.state
    ? this.props.location.state.from.pathname
    : "/";
  // 修改redux中的token值
  this.props.changeActive(true);
  // this.props.login();
  console.log(RedirectUrl);
  // 登陆成功之后的跳转
  this.props.history.push(RedirectUrl);
  };
  render() {
    return (
      <div>
        Login
        <button onClick={this.login}>Login</button>
      </div>
    );
  }
}
const mapStateToProps = (state, ownProps) => {
    return {
      token: state.token
    };
  };
const mapDispatchToProps = { changeActive };
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login);

//app.js
class App extends React.Component {
  render() {
    const { token } = this.props;
    return (
           {routerMap.map((item, index) => {
              return (
                  <Route
                    render={v =>
                     token ? ( <item.component {...v} />) :
                             ( <Redirect to={{  pathname: "/login", state: { from: v.location }  }}  />  )
            })}
const mapStateToProps = (state, ownProps) => {
  return {
    token: state.token
  };
};
export default connect(mapStateToProps)(App);
  • redux数据增删
import React, { Component } from "react";
import { connect } from "react-redux";
import { addMusicList, delMusicList } from "../../redux/actions/music";
class Music extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputVal: ""
    };
  }
  componentDidMount() {}
  handleChange = e => {
    this.setState({
      inputVal: e.target.value
    });
  };
  addMusic = () => {
    const list = this.props.musicList;
    const id = list[list.length - 1].id;
    this.props.addMusicList({ id: id + 1, name: this.state.inputVal });
  };
  delMusic = id => {
    this.props.delMusicList(id);
  };
  render() {
    const { musicList } = this.props;
    return (
      <div>
        <span>music</span>
        <input type="text" onChange={this.handleChange} />
        <button onClick={this.addMusic}>add</button>
        <ul>
          {musicList &&
            musicList.map((v, k) => (
              <li key={k}>
                {v.id} {v.name}
                <button onClick={() => this.delMusic(v.id)}>delete</button>
              </li>
            ))}
        </ul>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return {
    musicList: state.musicData1
  };
};
const mapDispatchToProps = { addMusicList, delMusicList };
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Music);

相关文章

  • react 001

    https://github.com/daisylys/react-0807 脚手架 create-react-a...

  • react -- 001

    React核心原理 当数据发生变化时,UI 能够自动把变化反映出来。 在 React 之前,我们需要调用 DOM ...

  • React入门-001

    +++Categories = ["React",]Tags = ["React","入门",]date = "2...

  • 001|什么是React?

    什么是React?官方的一句话解释是“A JAVASCRIPT LIBRARY FOR BUILDING USER...

  • react-native - 常用终端命令

    001 更新react-native的node依赖包请去下面的网址查看react-native的npm包的最新版本...

  • 02、React系列之--FlexBox

    本篇demo下载地址https://github.com/githubchen001/react-lesson/t...

  • 04 React 语法--001--React 偶遇

    ReactNative的入门学习指引 2020年上半年,自己学了一段时间Flutter,而在后半场的面试中,新的岗...

  • 001--Uncaught SyntaxError: Unexp

    问题 001 解决方法:1、在引入react组件的src 上增加 type="text/babel"2、引入

  • 001.react环境搭建

    1. react的优势 响应式更新 组件化 jsx声明式编程 多平台性 2. 创建工程的方式:2.1:react的...

  • 001@React Native 学习之了解RN技术

    001@React Native 学习之了解RN技术 简介: 作者 :一枚iOS开发的程序猿开发平台: Mac开发...

网友评论

      本文标题:react 001

      本文链接:https://www.haomeiwen.com/subject/wzlwdctx.html