React-Redux - 创建一个隐藏容器的动作

时间:2016-10-18 09:00:36

标签: javascript reactjs redux react-redux

我有2个按钮,一个用于显示我的工作细节,另一个用于隐藏它。显示详细信息的按钮正在工作,但现在我需要在单击隐藏详细信息按钮时隐藏详细信息容器。

我希望我能很好地解释自己,请问我是否需要更多信息。

这是我的miristica.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectTrabalho } from '../../actions/index';
import { hideDetails } from '../../actions/hide_details';
import TrabalhoMiristica from './detalhe_miristica';

class Miristica extends Component {

renderList(){

    return this.props.trabalho_m.map((trabalho) => {
        return (
            <li>
                <div className="row list-group">
                    <div className="col-md-4">
                        <img src={trabalho.img} />
                    </div>
                    <div className="col-md-8">
                        <h3>{trabalho.title}</h3>
                        <p>{trabalho.descricao}</p>
                        <button key={trabalho.id} onClick={() => this.props.selectTrabalho(trabalho)} type="button" className="show-detail btn btn-info">Detalhes</button>
                        <br/>
                        <br/>
                        <button onClick={() => this.props.hideDetails(trabalho)} type="button" className="btn btn-info">Esconder Detalhes</button>
                        <br/>
                        <br/>
                        <TrabalhoMiristica/>
                    </div>
                </div>
            </li>
        );
    })
    }

  render() {

  return (

    <ul className="list-group col-ms-4"> 
        {this.renderList()}
    </ul>

    );

  }
}


function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m
};
}

function mapDispatchToProps(dispatch) {

return bindActionCreators({ selectTrabalho: selectTrabalho, hideDetails: hideDetails }, dispatch)
}


export default connect(mapStateToProps, mapDispatchToProps)(Miristica);

这是我的hide_detail.js Actiom

export function hideDetails(id, trabalho) {

return {
    type: 'HIDE_DETAILS',
    id,
    trabalho
};

}

这是我的reducer_hide_detail.js

export default function(state = {hideDetails: true}, action) {
switch(action.type) {
case 'HIDE_DETAILS':
    console.log("remove detail");   
}

return state;
}

这是我的详细视图

import React, { Component } from 'react';
import { connect } from 'react-redux';

class TrabalhoMiristica extends Component {
render() {
    if (!this.props.trabalho) {
        return null;
    }

    return (
        <div>
            <div>{this.props.trabalho.tec}</div>
        </div>
    );
}
}

function mapStateToProps(state){
return {
    trabalho: state.activeMiristica
};
}


export default connect(mapStateToProps)(TrabalhoMiristica);

我有一个简单的控制台日志,当我点击按钮时它正常工作。 所以我只需要做一些动作让按钮工作,但我没有得到:(。有人可以帮助我吗?先谢谢。

更新:

这是trabalho_m的来源,来自我的带有数组的reducer

import { combineReducers } from 'redux';
- > import TrabalhoMiristica from './miristica/reducer_miristica';
import ActiveMiristica from './miristica/reducer_detalhe_miristica';
- > HIDE DETAIL REDUCER import HideDetails from './miristica/reducer_hide_detail';
import TrabalhoVet from './vet/reducer_vet';
import ActiveVet from './vet/reducer_detalhe_vet';

const rootReducer = combineReducers({

- > trabalho_m: TrabalhoMiristica,
trabalho_vet: TrabalhoVet,
activeMiristica: ActiveMiristica,
- > hideDetails: HideDetails,
activeVet : ActiveVet,


});

export default rootReducer;

Reducer Miristica

export default function() {

return [

    { id: 2, title: 'Miristica', tec: "Wordpress-Woocommerce", descricao: "Ustedes pueden aceptar mi negocio o aceptar las consequências. ¿Plata o plomo? Compremos una lavadora más grande, pues. Los políticos se espantan fácil. Una pistola y ya. La cárcel em Estados Unidos es peor que la muerte. El castillo, la torre yo soy. La espada que guarda el caudal. Tu el aire que respiro yo. Y la luz de la luna en el mar. La garganta que ansio mojar. Que temo ahogar de amor. Y cuales deseos me vas a dar? Dices tu: mi tesoro basta con mirarlo. Y tuyo será, y tuyo será", img: 'http://feiraalternativa.pt/wp-content/uploads/2016/04/Miristica-Bio-Cosm%C3%A9tica.png'},

];

}

非常感谢您的帮助!!

UDPDATE -

Reducers index.js

import { combineReducers } from 'redux';
import TrabalhoMiristica from './miristica/reducer_miristica';
import ActiveMiristica from './miristica/reducer_detalhe_miristica';
import HideDetails from './miristica/reducer_hide_detail';
import TrabalhoVet from './vet/reducer_vet';
import ActiveVet from './vet/reducer_detalhe_vet';

const rootReducer = combineReducers({

trabalho_m: TrabalhoMiristica,
trabalho_vet: TrabalhoVet,
activeMiristica: ActiveMiristica,
hideDetails_m: HideDetails,
activeVet : ActiveVet,


});

export default rootReducer;

我已将reducer的名称更改为hideDetails_m,并且我已更新了stateToProps函数

function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m,
    hideDetails_m: state.hideDetails_m
};
}

现在我不明白你在哪里

{ this.props. - > detailsHidden <- ? null : (
 <TrabalhoMiristica/>
)}

谢谢

更新 -

Miristica.js



return this.props.trabalho_m.map((trabalho) => {
        return (
            <li>
                <div className="row list-group">
                    <div className="col-md-4">
                        <img src={trabalho.img} />
                    </div>
                    <div className="col-md-8">
                        <h3>{trabalho.title}</h3>
                        <p>{trabalho.descricao}</p>
                        <button key={trabalho.id} onClick={() => this.props.selectTrabalho(trabalho)} type="button" className="show-detail btn btn-info">Detalhes</button>
                        <br/>
                        <br/>
                        <button onClick={() => this.props.hideDetails(trabalho)} type="button" className="btn btn-info">Esconder Detalhes</button>
                        <br/>
                        <br/>
                        { this.props.detailsHidden ? null : (
                            <TrabalhoMiristica/>
                        )}
                    </div>
                </div>
            </li>
        );
    })
}

function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m,
    hideDetails_m: state.detailsHidden
};
}

REDUCER reducer_hide_details.js

  export default function(state = {hideDetails: true}, action) {
  switch(action.type) {
  case 'HIDE_DETAILS':
  return Object.assign({}, state, {
   hideDetails: true
  }); 
  default:
  return state;
  }
  }

Index.js Reducers

import { combineReducers } from 'redux';
import TrabalhoMiristica from './miristica/reducer_miristica';
import ActiveMiristica from './miristica/reducer_detalhe_miristica';
import HideDetails from './miristica/reducer_hide_detail';
import TrabalhoVet from './vet/reducer_vet';
import ActiveVet from './vet/reducer_detalhe_vet';

const rootReducer = combineReducers({

trabalho_m: TrabalhoMiristica,
trabalho_vet: TrabalhoVet,
activeMiristica: ActiveMiristica,
hideDetails_m: HideDetails,
activeVet : ActiveVet,


});

export default rootReducer;

我必须将我的状态传递给我的地图功能吗?请帮忙。感谢

更新

喜欢这个?

{ this.props.hideDetails_m.hideDetails ? null : (
    <TrabalhoMiristica/>
)}


function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m,
    hideDetails_m: state.hideDetails_m.hideDetails
};
}

UPDATE SyntaxError:意外的令牌(11:8)

reducer_miristica.js

const initialState = [
{ showDetails: true,  id: 2, title: 'Miristica', tec: "Wordpress-   Woocommerce", descricao: "Ustedes pueden aceptar mi negocio o aceptar las consequências. ¿Plata o plomo? Compremos una lavadora más grande, pues. Los políticos se espantan fácil. Una pistola y ya. La cárcel em Estados Unidos es peor que la muerte. El castillo, la torre yo soy. La espada que guarda el caudal. Tu el aire que respiro yo. Y la luz de la luna en el mar. La garganta que ansio mojar. Que temo ahogar de amor. Y cuales deseos me vas a dar? Dices tu: mi tesoro basta con mirarlo. Y tuyo será, y tuyo será", img: 'http://feiraalternativa.pt/wp-content/uploads/2016/04/Miristica-Bio-Cosm%C3%A9tica.png'},
]

export default function(state = initialState, action) {
switch(action.type) {
case 'HIDE_DETAILS':
  return state.map(function(item){
    if (item.id == action.id) {
      return Object.assign({}, state, { showDetails: false }
    }
    return item;
  });
 default:
  return state;
 }
}

我把它放在了巴贝尔验证器上

repl: Unexpected token (11:8)
9 |         if (item.id == action.id) {
10 |           return Object.assign({}, state, { showDetails: false }
11 |         }
   |         ^

谢谢!

更新

detail_miristica.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class TrabalhoMiristica extends Component {
render() {
    if (!this.props.trabalho) {
        return null;
    }

    return (
        <div>
            <div>{this.props.trabalho.tec}</div>
        </div>
    );
}
}

function mapStateToProps(state){
return {
    trabalho: state.activeMiristica
};
}


export default connect(mapStateToProps)(TrabalhoMiristica);

在阵列中我有tec:&#39; Wordpress-woocomerce&#39;我在细节中表明了这一点。

谢谢!!

1 个答案:

答案 0 :(得分:3)

首先,您必须将详细信息视图包含在引用state.hideDetails的if语句中。 (我在你的问题中找不到你的详细信息)

但我认为你问题的主要部分是如何在减速器中做什么。在你的减速机中,你必须返回新的状态。因此,如果您要执行'HIDE_DETAILS操作,则需要返回:

return { hideDetails: true }

如果您想为状态对象添加更多字段,这会很快崩溃。因此,我建议使用Object.assign。所以你的减速器看起来像这样:

export default function(state = {hideDetails: true}, action) {
  switch(action.type) {
    case 'HIDE_DETAILS':
      return Object.assign({}, state, {
       hideDetails: true
      }); 
    default:
      return state;
    }
}

修改

好的,根据您的评论,我认为您仍然需要帮助将您的详细信息视图包装在条件中。

我不太明白这个trabalho_m州的来源,但您必须添加state.hideDetails或者如果您要将多个缩减器合并到state.detailReducer.hideDetails(假设减速器)被命名为detailReducer到您的mapStateToProps函数。请注意命名冲突,因为您的操作也被命名为hideDetails

无论如何you can't use if-else-statements in JSX因此你应该尝试这样的事情:

{ this.props.detailsHidden ? null : (
  <TrabalhoMiristica/>
)}

编辑2:

您的命名不同,并且您没有像我想的那样将道具映射得很深。所以在你的情况下,它将是:

{ this.props.hideDetails_m.hideDetails ? null : (
  <TrabalhoMiristica/>
)}

编辑3:

既然我已经阅读了你再次添加的所有内容,我注意到我错过了你可能想要保存隐藏状态而不是全局而是保存在trabalho上。

我认为最好的方法是将hiddenDetails_m全部放在一起并将其存储在trabalho_m州。

所以reducers / index.js将是:

import { combineReducers } from 'redux';
import TrabalhoMiristica from './miristica/reducer_miristica';
import ActiveMiristica from './miristica/reducer_detalhe_miristica';
import TrabalhoVet from './vet/reducer_vet';
import ActiveVet from './vet/reducer_detalhe_vet';

const rootReducer = combineReducers({

  trabalho_m: TrabalhoMiristica,
  trabalho_vet: TrabalhoVet,
  activeMiristica: ActiveMiristica,
  activeVet : ActiveVet,


});

export default rootReducer;

而reducers / reducer_miristice.js将是:

const initialState = [
  { showDetails: true,  id: 2, title: 'Miristica', tec: "Wordpress-Woocommerce", descricao: "Ustedes pueden aceptar mi negocio o aceptar las consequências. ¿Plata o plomo? Compremos una lavadora más grande, pues. Los políticos se espantan fácil. Una pistola y ya. La cárcel em Estados Unidos es peor que la muerte. El castillo, la torre yo soy. La espada que guarda el caudal. Tu el aire que respiro yo. Y la luz de la luna en el mar. La garganta que ansio mojar. Que temo ahogar de amor. Y cuales deseos me vas a dar? Dices tu: mi tesoro basta con mirarlo. Y tuyo será, y tuyo será", img: 'http://feiraalternativa.pt/wp-content/uploads/2016/04/Miristica-Bio-Cosm%C3%A9tica.png'},
]


export default function(state = initialState, action) {
  switch(action.type) {
    case 'HIDE_DETAILS':
      return state.map(function(item){
        if (item.id == action.id) {
          return Object.assign({}, item, { showDetails: false }
        }
        return item;
      });
    default:
      return state;
  }
}

这意味着你的组件看起来像这样:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectTrabalho } from '../../actions/index';
import { hideDetails } from '../../actions/hide_details';
import TrabalhoMiristica from './detalhe_miristica';

class Miristica extends Component {

renderList(){

    return this.props.trabalho_m.map((trabalho) => {
        return (
            <li>
                <div className="row list-group">
                    <div className="col-md-4">
                        <img src={trabalho.img} />
                    </div>
                    <div className="col-md-8">
                        <h3>{trabalho.title}</h3>
                        <p>{trabalho.descricao}</p>
                        <button key={trabalho.id} onClick={() => this.props.selectTrabalho(trabalho)} type="button" className="show-detail btn btn-info">Detalhes</button>
                        <br/>
                        <br/>
                        <button onClick={() => this.props.hideDetails(trabalho)} type="button" className="btn btn-info">Esconder Detalhes</button>
                        <br/>
                        <br/>
                        { trabalho.showDetails ? (
                          <TrabalhoMiristica/>
                        ) : null }
                    </div>
                </div>
            </li>
        );
    })
    }

  render() {

  return (

    <ul className="list-group col-ms-4"> 
        {this.renderList()}
    </ul>

    );

  }
}


function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m
};
}

function mapDispatchToProps(dispatch) {

return bindActionCreators({ selectTrabalho: selectTrabalho, hideDetails: hideDetails }, dispatch)
}


export default connect(mapStateToProps, mapDispatchToProps)(Miristica);

编辑3.1:

我没有添加任何有关此操作的信息。

你的动作需要一个id和一个trabalho但你只能在你的组件中传递一个trabalho。我认为你现在不需要trabalho,所以只需传递身份证。这就是我在减速机方面的假设。你的行动将是这样的:

export function hideDetails(id) {

return {
    type: 'HIDE_DETAILS',
    id,
};

你必须在组件中更改它:

<button onClick={() => this.props.hideDetails(trabalho)} type="button" className="btn btn-info">Esconder Detalhes</button>

为:

<button onClick={() => this.props.hideDetails(trabalho.id)} type="button" className="btn btn-info">Esconder Detalhes</button>

}

编辑4:

我认为我们远远超出了您的问题的范围,但您的主要警告是由于未将唯一密钥传递给<li>。 (阅读更多关于here.

的信息

所以你的组件现在看起来像这样。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectTrabalho } from '../../actions/index';
import { hideDetails } from '../../actions/hide_details';
import TrabalhoMiristica from './detalhe_miristica';

class Miristica extends Component {

renderList(){

    return this.props.trabalho_m.map((trabalho) => {
        return (
            <li key={trabalho.id}>
                <div className="row list-group">
                    <div className="col-md-4">
                        <img src={trabalho.img} />
                    </div>
                    <div className="col-md-8">
                        <h3>{trabalho.title}</h3>
                        <p>{trabalho.descricao}</p>
                        <button key={trabalho.id} onClick={() => this.props.selectTrabalho(trabalho)} type="button" className="show-detail btn btn-info">Detalhes</button>
                        <br/>
                        <br/>
                        <button onClick={() => this.props.hideDetails(trabalho)} type="button" className="btn btn-info">Esconder Detalhes</button>
                        <br/>
                        <br/>
                        { trabalho.showDetails ? (
                          <TrabalhoMiristica/>
                        ) : null }
                    </div>
                </div>
            </li>
        );
    })
    }

  render() {

  return (

    <ul className="list-group col-ms-4"> 
        {this.renderList()}
    </ul>

    );

  }
}


function mapStateToProps(state) {

return {
    trabalho_m: state.trabalho_m
};
}

function mapDispatchToProps(dispatch) {

return bindActionCreators({ selectTrabalho: selectTrabalho, hideDetails: hideDetails }, dispatch)
}


export default connect(mapStateToProps, mapDispatchToProps)(Miristica);