const updateRouterArr = () => {
if (this.props.router_addr && this.props.router_username && this.props.router_pw) {
this.props.updateRouterArr({
router_addr: this.props.router_addr,
router_username: this.props.router_username,
router_pw: this.props.router_pw
})
} else {
alert('Some fields are missing')
}
}
export const RouterCard = (props) => {
return (
<div>
...
</div>
);
}
const mapStateToProps = state => ({
routers: state.router.routers,
router_addr: state.router.router_addr,
router_username: state.router.router_username,
router_pw: state.router.router_pw,
})
const mapActionsToProps = {
updateRouterElem: updateRouterElem,
updateRouterArr: updateRouterArr,
deleteRouterElem: deleteRouterElem,
}
export default connect(mapStateToProps, mapActionsToProps)(RouterCard);
我正在使用带有React-Redux的功能组件。当我尝试此操作时,它给了我Parsing error: Identifier 'updateRouterArr' has already been declared
我知道为什么会这样,但是我不确定在使用功能组件时如何正确使用React-Redux。
我已经声明了我需要执行的所有操作
const mapActionsToProps = {
updateRouterElem: updateRouterElem,
updateRouterArr: updateRouterArr,
deleteRouterElem: deleteRouterElem,
}
但是它很混乱,因为它不再识别this.props
。
我该如何解决?
答案 0 :(得分:1)
您只是不需要this.
之前的props
。功能组件将接受道具作为参数。
所以代码看起来像
// Assuming that updateRouterArr is global function
const updateRouterArr = (props) => {
if (props.router_addr && props.router_username && props.router_pw) {
props.updateRouterArr({
router_addr: props.router_addr,
router_username: props.router_username,
router_pw: props.router_pw
})
} else {
alert('Some fields are missing')
}
}
export const RouterCard = (props) => {
// And you can call it from RouterCard component
updateRouterArr(props);
return (
<div>
...
</div>
);
}
const mapStateToProps = state => ({
routers: state.router.routers,
router_addr: state.router.router_addr,
router_username: state.router.router_username,
router_pw: state.router.router_pw,
})
const mapActionsToProps = {
updateRouterElem: updateRouterElem,
updateRouterArr: updateRouterArr,
deleteRouterElem: deleteRouterElem,
}
export default connect(mapStateToProps, mapActionsToProps)(RouterCard);
简单的example
答案 1 :(得分:0)
您可以尝试这样做是否有帮助。我在mapActionsToProps中进行了一些更改,并使用对象分解来获取道具。道具可以使用相同的名称访问。
const updateRouterArr = (
{updateRouterElem, updateRouterArr, deleteRouterElem, routers, router_addr, router_username, router_pw}
) => {
if (router_addr && router_username && router_pw) {
updateRouterArr({
router_addr: router_addr,
router_username: router_username,
router_pw: router_pw
})
} else {
alert('Some fields are missing')
}
}
export const RouterCard = (props) => {
return (
<div>
...
</div>
);
}
const mapStateToProps = state => ({
routers: state.router.routers,
router_addr: state.router.router_addr,
router_username: state.router.router_username,
router_pw: state.router.router_pw,
})
const mapActionsToProps = {
updateRouterElem,
updateRouterArr,
deleteRouterElem,
}
export default connect(mapStateToProps, mapActionsToProps)(RouterCard);