【发布时间】:2017-04-20 09:02:47
【问题描述】:
`import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { itemsFetchData,toggleDiv } from
'../actions/sidenavaction';
class SideNavItem extends Component {
componentDidMount() {
this.props.fetchData
('http://58f5d2ccc9deb71200ceecef.mockapi.io/nav');
}
render() {
var Nest=function(par) {
const numbers = par.itemized;
const listItems = numbers.map((number) => <li
key={number.sid}>{number.svalue}</li>);
return (<ul>{listItems}</ul>);
};
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (
<ul>{this.props.items.map((item) =>
<ul key={item.id} onClick=
{this.props.toggleDiv.bind(this,item.id)}><a href="#">
{item.value}</a>
{item.sub && <div style={{display: this.props.hidden ? 'block' :
'none'}}><Nest itemized={item.sub} /></div>}
</ul>
)}
</ul>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading,
hidden:state.toggleDivReducer.hidden
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url)),
toggleDiv: (id) => dispatch(toggleDiv(id))
};
};
export default connect(mapStateToProps, mapDispatchToProps)
(SideNavItem);`
我可以将 id 传递给我的操作 mapdispatchtoprops,但我也希望 onclick 仅在我单击的元素上触发,并且我已经实现了切换,但在哪里应用隐藏道具,因为当我加载列表时嵌套列表没有隐藏,但点击链接我可以切换它们Onload the nested links are also visible whereas it should be hidden
动作 ` 导出函数 toggleDiv(id){ 返回 { 类型:'TOGGLE_DIV', 身份证号:身份证
};
}`
减速器 `导出函数toggleDivReducer(状态= {隐藏: 真},动作){ 开关(action.type){
case 'TOGGLE_DIV':
return Object.assign({}, state, {hidden:
!state.hidden});
default:
return state;
}
}
【问题讨论】:
-
onClick= {this.props.toggleDiv.bind(this,item.id)} ,我如何编写一个函数来执行 event preventdefault 并将 id 传递给我的 mapdispatchtoprops 以及我的切换是没有按预期工作,我的意思是在加载时嵌套值也会显示,但是当我切换时它会隐藏,但这也适用于所有链接
-
好的我能够理解为什么 onClick 会被应用,因为我已经在 map 函数中给出了它,但是任何人都可以帮助我知道我应该将我放在哪里 onClick 以便它只适用于点击的元素