状态对象将rootReducer转换为CombineReducers的问题

时间:2018-07-31 19:37:35

标签: javascript reactjs redux

我有一个使用Redux的应用程序,该应用程序当前将reducer文件设置为rootReducer,但我需要对其进行扩展,因此我想使用CombineReducers,但无法正常工作。这是我的rootReducer的代码,在应用程序中可以正常运行

//Root Reducer

export default function rootReducer(state = {
    filtered: [],
  }, action) {

    switch (action.type) {
      case "SEARCH_IMAGES":
        let filtered = action.payload
       return {...state, images: action.payload, filtered, isFetching: false}
      
      default:
        return state
    }
  }
所以我创建了一个新的reducer,叫做filtered

export default function (state = {
  filtered: []}, action) {
  
  switch (action.type) {
   
    case "SEARCH_IMAGES":
      let filtered = this.state.action.payload
      return {
         ...state, images: action.payload, filtered, isFetching: false
      };
      default:
      return state
    }
}

设置组合的减速器索引文件以导入新的减速器

import { combineReducers } from 'redux';
import comments from './comments';
import filtered from './filtered';
import images from './images';

export default combineReducers({
  filtered, images
})
将其导入到我的索引中,并将其添加到我的商店和提供商中。 问题似乎出在state = { filtered: []
参数。如何使用组合的异径管在新的异径管中工作。如何为filtered: []

添加空数组

这是我收到的错误消息 enter image description here

这是经过修订的ImageContainer.js

import React from 'react'
import ImageCard from './ImageCard'
import ContentLoader from 'react-content-loader'


class ImageContainer extends React.Component {
 
  render() {
    const { filtered } = this.props;
    const allImages = this.props.filtered.filtered.map((pic) => {
        return <ImageCard key={pic.id} pic={pic} url={pic.images[0]["link"]} />
    })
    return (
  
      <div className="image-wrapper">
        {allImages}
        <div className="note">
      {allImages.length === 0 ? "No memes are set for this query tag": ""}
      </div>
      </div>
     
    )
  }
}

export default ImageContainer
门户页面

import React from 'react'
import { Label } from 'semantic-ui-react'
import * as IchingTable from '../../constants/lookup.js';
import { HexagramImage } from '../HexagramImage.js';
import * as pictureActions from '../../actions/pictures'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import ImageContainer from './ImageContainer.js';
import ReactDOM from 'react-dom'
import classnames from 'classnames';
import { Segment } from 'semantic-ui-react'
import { NavLink, withRouter} from 'react-router-dom';


class PortalPage extends React.Component {

  constructor(props) {
    super(props);
    
    this.state = {
      open: false,
      selectedTabId: 1,
      intervalId: null
    }
    
  }  
  componentDidMount() {
   
    let query = this.props.hexagram.tags[0].label 
    this.props.searchImages(query)
  }


 
 


  detailsback(hex) {
    
    this.props.history.push( `/details/${hex.number}/${hex.name}` );
    this.props;
    console.log("this is the bar hex");
    
  }
  
  
  labelClick = (label, event, selectedTabId, id) => {
    event.preventDefault();
    let query = event.target.innerText;    
    const { searchImages } = this.props
    searchImages(query);
    this.setState({ selectedTabId : label.id });
  }
  render() {
    let hexNumber = Number( this.props.match.params.number );
    let hex  = IchingTable.getHexagram( hexNumber );
    let {trigrams, name, number, description, tags, selectedTabId} = this.props.hexagram;
      let searchtags = (tags).map( (tag, label, id, index) => {
        let initActive = (match, location) => {
          if (!match) {
            return false
          }
          let selectedTabId = parseInt(match.selectedTabId)
          return this.state.selectedTabId === tag.id;
        }
    
        const params = new URLSearchParams(this.props)
        return (
          <div className="labeltags" key={label} >
          <Label 
              onClickCapture={this.labelClick.bind(null, tag)} 
              as={NavLink}
              to="/"
              activeClassName="slabel--active"
              basic size={'large'} 
              value={tag.id}
              key={label} 
              isActive={initActive}
              >
              {tag.label}
            </Label>
          </div>   
        );
      })
      
    return (
      <div>

          <Segment raised>
          <Label
            as='a'
            onClick={this.detailsback.bind(this, hex)}
            onTouchTap={this.detailsback.bind(this, hex)}
            ribbon='right'
            color='orange'
            >
             &#x2190; Back
            </Label> 
          <div className="hexagram-card">
            <HexagramImage below={trigrams.below} above={trigrams.above} />
            <div className="title">
              <h3>{number}: {name}</h3>
              <h2>{description}</h2>
            </div>
            
          </div>
          </Segment>
         
            <div>
            <p>Click on search terms for </p><h4>{name} - {description} </h4>
             {searchtags}
             
            </div>
          <div>
            <ImageContainer filtered={this.props.filtered} />
          </div>
         
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    filtered: state.filtered
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(pictureActions, dispatch)
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PortalPage))

2 个答案:

答案 0 :(得分:0)

能否请您分享您遇到的错误?

查看您的代码,我看到一个错误(下面是经过纠正的代码):

export default function (state = {
  filtered: []}, action) {

  switch (action.type) {

    case "SEARCH_IMAGES":
      // calling this.state.action.payload is incorrect. "action" variable contains the payload
      let filtered = action.payload // Old Code - this.state.action.payload
      return {
         ...state, images: action.payload, filtered, isFetching: false
      };
      default:
      return state
    }
}

答案 1 :(得分:0)

  

您的问题还不清楚。但是我能弄清楚的是你   想知道如何与联合减速机一起工作

这就是我们使用联合减速器的方式

reducer1.js

const somedefault = [];
    export default function (state = somedefault, action) {

      switch (action.type) {

        case "SEARCH_IMAGES":
          let filtered = action.payload
          return {
             ...state, images: action.payload, filtered, isFetching: false
          };
          default:
          return state
        }
    }

reducer2.js

const somedefault = {};
    export default function (state = somedefault, action) {

      switch (action.type) {
          default:
             return state
        }
    }

combineReducer.js

import { combineReducers } from 'redux';
import Red1 from './reducer1.js';
import Red2 from './reducer2.js';

export default combineReducers({
  red1: Red1,
  red2: Red2
})

因此,当您看到自己的redux状态时,它将看起来像

state
|___red1: []
|___red2: {}