react基礎(chǔ)

  1. 基本語(yǔ)法

    • ReactDOM.render():渲染虛擬dom,注意大小寫

    • map方法生成列表arr .map(function(value){})

    • 可以直接插入變量

      var arr = [
        <h1>Hello world!</h1>,
        <h2>React is awesome</h2>,
      ];
      ReactDOM.render(
        <div>{arr}</div>,
        document.getElementById('example')
      );
      
    • 處理子節(jié)點(diǎn):``React.Children.map,獲取子節(jié)點(diǎn)this.props.children`

    • 通過propTypes定義屬性類型React.PropTypes.string.isRequired ,定義初始屬性:

      getDefaultProps : function () {
          return {
            title : 'Hello World'
          };
        },
      
    • 獲取真實(shí)節(jié)點(diǎn)this.refs.name

    • 初始化state getInitialState

    • 組件的生命周期,前三個(gè)周期都有兩種狀態(tài)will did

      • Mounting: 載入

      • Updating:正在被重新渲染

      • Unmounting:已移除真實(shí)DOM

      • componentWillReceiveProps(object nextProps):已加載組件收到新的參數(shù)時(shí)調(diào)用

      • shouldComponentUpdate(object nextProps, object nextState):組件判斷是否重新渲染時(shí)調(diào)用

        component-lifecycle
        component-lifecycle
  `
 class App extends React.Component {
 // Mounting:
 componentWillMount() {
   // 1. 這是第一次 render 前,更新 state 的最後機(jī)會(huì):
   this.setState({ ageText: this.props.age + '歲' });
 }

 // Mounting:
 componentDidMount() {
   // 1. 如果你要操作實(shí)際的 DOM 元素:
   $('#app').hide();

   // 2. 如果你要請(qǐng)求 AJAX,或是設(shè)置 timer:
   $.ajax({ ... });
 }

 // Updating:
 componentWillReceiveProps(nextProps) {
   // 1. 如果你要根據(jù)新的 props 做一些運(yùn)算:
   this.setState({ ageText: nextProps.age + '歲' });
 }

 // Updating:
 shouldComponentUpdate(nextProps, nextState) {
   // 1. 如果你想調(diào)校元件效能,不想要做沒有意義的 re-render,
   //    如下方只有在 id 不相同的情況下再 render 的話:
   return nextProps.id !== this.props.id;
 }

 // Updating:
 componentWillUpdate(nextProps, nextState) {
   // 1. 這是第 N 次 render 前,最後被調(diào)用的方法,
   //    通常可以拿來(lái)做 log
 }

 // Updating:
 componentDidUpdate(prevProps, prevState) {
   // 1. 如果你要操作更新後實(shí)際的 DOM 元素:
   $('#app').hide();
 }

 // Unmounting:
 componentWillUnmount() {
   // 1. 如果該元件消滅,也需要移除不必要的 AJAX 請(qǐng)求的話:
   xhr.abort();

   // 2. 如果你要移除不必要的傾聽事件:
   store.removeChangeListener(...);
 }
 }
  1. react建立組件的三種方式

    • 使用es6的類

      class TodoList extends React.Component{
        render(){
          
        }
      }
      
    • 使用createClass

      const TodoList = React.createClass({
        render(){
          return (<div>todolist</div>)
        }
      })
      
    • 使用無(wú)狀態(tài)函數(shù)

      const TodoList = function(){
        return <div>todoapp</div>
      }
      

      ?

  2. 通過屬性props傳遞參數(shù)給子組件{title,name,...rest}=this.props ,還可以這樣添加屬性

    const props = {
      name:'nico',
      age:18
    }
    render(){
      return <div {...props} ></div>
    }
    //使用function時(shí)時(shí)通過參數(shù)獲得的
    function Todo(props){
      
    }
    const Todo=(props)=>(<div></div>)
    const Todo =({name,age})=>(<div><div>)
    
    //相關(guān)知識(shí)點(diǎn)
    //組合對(duì)象
    const firstName = 'Jason';
    const lastName = 'Chung';
    const others = {
      sex: 'male',
      age: 27
    };
    const user = {firstName,lastname,...others}
    
  3. 防止類型錯(cuò)誤,可以給組件設(shè)置屬性類型

    Todo.propTypes={
      title:React.PropTypes.string,
      age:React.PropTypes.number
    }
    
  4. 動(dòng)態(tài)添加列表

    render(){
      <div>
      {this.props.todos.map((todo)=>{
        <li>{todo.name}</li>
      })}
      </div>
    }
    
  5. 過濾器filter

    arr.filter((state)=>{
      return number>9
    })
    
  6. css module

    • :local 為局部變量,默認(rèn)
    • :global 全局變量
    • 組合class composes:classname
  7. this.props.children 表示組件所有的子節(jié)點(diǎn)

  8. fetch獲取數(shù)據(jù)

    fetch('./todos.json')                         // 1. 使用 fetch 回傳的是 promise 物件
        .then((response) => response.json())        // 2. 解析 response 資料,將它轉(zhuǎn)成 js 物件
        .then((todos) => this.setState({ todos })); // 3. 更新元件 state
    
    //使用方法
    const promise = new Promise((resolve, reject) => {
      // resolve 用來(lái)傳遞非同步的成功結(jié)果,例如:AJAX 最後取得的資料或一秒後定義的值
      // reject 用來(lái)傳遞非同步的錯(cuò)誤結(jié)果
      setTimeout(() => resolve('async'), 1000);
    });
    
    promise
      .then((res) => console.log(res))   // 透過 promise.then 可以先定義非同步成功後,要執(zhí)行什麼
      .catch((err) => console.log(err)); // 透過 promise.catch 可以先定義非同步錯(cuò)誤後,要執(zhí)行什麼
    
    • 相關(guān)api:

      const url = '/login';
      const options = {
        method: 'POST',
        headers: {}
      };
      
      fetch(url, options)           // 使用 fetch 調(diào)用 AJAX 回傳 promise 物件
        .then((res) => res.json());
      
  9. redux流程

img
img
let listeners = []
// 1. Redux 中只會(huì)有一個(gè)狀態(tài)樹,統(tǒng)一存放所有業(yè)務(wù)資料
let state

// 2. 每當(dāng)使用者觸發(fā)事件,調(diào)用 store.dispatch(action)
function dispatch(action) {
  // 3. 根據(jù) reducer 取得最新的狀態(tài)
  state = reducer(state, action)
  // 4. 通知所有傾聽器 store 的狀態(tài)已改變
  listeners.slice().forEach(l => l())
}

// 5. 當(dāng) view 知道 Store 狀態(tài)改變,呼叫 getter API 取得最新狀態(tài)
function getState() {
  return state
}

// 6. 讓 view 註冊(cè)狀態(tài)改變的傾聽器
function subscribe(listener) {
  listeners.push(listener)
  // 7. 回傳 unsubscribe 函數(shù)
  return () => listeners.filter((l) => l !== listener)
}
  1. 注意apply應(yīng)用

    function foo(x, y, z) {}
    const args = [1,2,3];
    
    // 下面兩句效果相同
    foo.apply(null, args);
    foo(...args);
    
  2. generator

    app.model({
      namespace:'todos',
      effects:{
        *addRemote({payload:todo},{put,call}){
          yield call(addTodo.todo);
      yield put({type:'add',payload:tod})
        }
      }
    })
    
  3. img
    img

14.當(dāng)有多個(gè)屬性時(shí)classnames
import classnames from 'classnames'; const App = (props) => { const cls = classnames({ btn: true, btnLarge: props.type === 'submit', btnSmall: props.type === 'edit', }); return <div className={ cls } />; }

  1. dva的model
      app.model({
      namespace: 'todos',
      state: [],
      reducers: {
        add(state, { payload: todo }) {
          return state.concat(todo);
        },
        remove(state, { payload: id }) {
          return state.filter(todo => todo.id !== id);
        },
        update(state, { payload: updatedTodo }) {
          return state.map(todo => {
            if (todo.id === updatedTodo.id) {
              return { ...todo, ...updatedTodo };
            } else {
              return todo;
            }
          });
        },
      },
      };
    

dva的簡(jiǎn)單使用

使用dva-cli:

? 生成路由:dva g route routerName

? 生成model:dva g model modelName

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容