React入門(mén)(六) Redux

本節(jié)知識(shí)點(diǎn)

(1) 簡(jiǎn)介Redux作用
(2) 使用Redux

(一) Redux介紹

Redux 就是相當(dāng)于Vue中的 Vuex 存放公共數(shù)據(jù)的地方。比如兄弟之間傳值等等

(二) 使用Redux

  • (1) 安裝
npm i redux -S
  • (2) 在src目錄下創(chuàng)建一個(gè)store文件夾,里面創(chuàng)建一個(gè)index.js文件作為公共倉(cāng)庫(kù)
import { createStore } from 'redux'
//引入reducer
import reducer from './reducer'
//放入reducer
const store = createStore(reducer)
export default store
  • (3) 創(chuàng)建reducer文件,他里面接收兩個(gè)參數(shù) state,action antion下篇在講,state就是獲取到所有的公共數(shù)據(jù)
const defaultState = {
  inputValue: '123',
  list: [
    'Racing car sprays burning fuel into crowd.',
    'Japanese princess to wed commoner.',
    'Australian walks 100km after outback crash.',
    'Man charged over missing wedding girl.',
    'Los Angeles battles huge wildfires.'
  ]
}
export default (state = defaultState, action) => {
  return state
}
  • (4) 組件里面引入
import React, { Component } from 'react'
import { Input, Button, List } from 'antd'
import 'antd/dist/antd.css'
//引入倉(cāng)庫(kù)文件
import store from './store/index'
class App extends Component {
  constructor(props) {
    super(props)
   // 獲取倉(cāng)庫(kù)數(shù)據(jù)的話就是store.getState();
    console.log(store.getState())
    //輸出的結(jié)果就是indexValue,list
    this.state = store.getState()
  }
  render() {
    return (
      <div>
        <Input
          placeholder="Basic usage"
          value={this.state.inputValue}
          onChange={this.cahngevalue.bind(this)}
          style={{ width: '300px', marginRight: '20px' }}
        />
        <Button type="primary" onClick={this.change.bind(this)}>
          提交
        </Button>
        <List
          style={{ width: '300px', marginTop: '20px' }}
          header={<div>Header</div>}
          footer={<div>Footer</div>}
          bordered
          dataSource={this.state.list}
          renderItem={item => <List.Item>{item}</List.Item>}
        />
      </div>
    )
  }
  change(e) {
    console.log(e.target)
  }
  cahngevalue(e) {
    let value = e.target.value
    this.setState({
      value
    })
  }
}

export default App


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容