关于redux存取值和跳转传值

381 阅读1分钟

1.目录

  • redux取值
  • redux存值
  • 跳转传值

2.实例

store文件下的index.js

import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store

store文件下的reducer.js

const datalist = {
    username: ''
}
const redu = (state = datalist, action) => {
    if(action.type==='input-username'){
        let newlist=JSON.parse(JSON.stringify(state))
        newlist.username=action.value
        return newlist
    }
    return state
}
export default redu

Home文件下的index.js

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'

export class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  render() {
    return (
      <div>
        <input placeholder='请输入账号' value={this.props.username} onChange={(e) => { this.props.inputBtn(e) }} />
      </div>
    )
  }
}
const a = (state) => {
  return {
    ...state
  }
}

const b = (dispatch) => {
  return {
    inputBtn(e) {
      let action = {
        type: 'input-username',
        value: e.target.value
      }
      dispatch(action)
    },
  }
}
export default connect(a, b)(withRouter(Home))

以上是redux存取值,接下来是跳转传值

HomeTwo文件下的index.js

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

export class HomeTwo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      id: 1
    }
  }
  goBtn() {
    this.props.history.push(`/home/one/${this.state.id}`)
    //下面两种方法也可以跳转传值,刷新后会报错
    // this.props.history.push({ pathname: '/home/one', query: { id: this.state.id } })
    // this.props.history.push({ pathname: '/home/one', state: { id: this.state.id } })
  }
  render() {
    return (
      <div>HomeTwo
        <span onClick={() => { this.goBtn() }}>跳转传值</span>
      </div>
    )
  }
}

export default withRouter(HomeTwo)

HomeOne文件下的index.js

import React, { Component } from 'react'

export class HomeOne extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  componentDidMount() {
    console.log(this.props.match.params.id)
    //下面两种方法也可以跳转传值,刷新后会报错
    //console.log(this.props.location.query.id)
    //console.log(this.props.location.state.id)
  }
  render() {
    return (
      <div>
          HomeOne
          {this.props.match.params.id}
      </div>
    )
  }
}

export default HomeOne