【发布时间】:2021-08-23 19:14:10
【问题描述】:
我有一个我调用的组件,它传递了一个记录 ID,并返回与该 ID 关联的文本。 33 应该 = 塔
将在屏幕上呈现“塔”。都很好,但是...
当我尝试在以下 IF 语句中使用该组件时,它不起作用。
...
if (<GetAssetTypeNameComponent datafromparent = {assettype_assettypeId}/> === "Tower")
{
this.props.history.push(`/add-assetstower/${assetsid}/${this.props.match.params.sitemasterid}`);
}
如果我将代码更改为:使用传递的参数确实有效:
...
if (assettype_assettypeId === "33")
{
this.props.history.push(`/add-assetstower/${assetsid}/${this.props.match.params.sitemasterid}`);
}
...
我做错了什么?
罗伯
需要成为函数的组件代码.... ...
class GetAssetTypeNameComponent extends Component {
constructor (props){
super(props)
this.state = {
assettype:[]
}
}
componentDidMount()
{
AssetTypeService.getAssetTypeById(this.props.datafromparent).then( (res) =>{
let assettype = res.data;
this.setState({isLoading:false});
this.setState({
assettypeName: assettype.assettypeName,
assettypeType: assettype.assettypeType
});
});
}
render() {
return (
<div>
{this.state.assettypeName}
</div>
);
}
}
export default GetAssetTypeNameComponent;
... 以下函数代码编译: ...
import React, { useState} from 'react';
import AssetTypeService from './AssetTypeService'
const GetAssetTypeNameFunction = (props) =>{
// destructuring
const { assettype_assettypeId } = props;
const [assetType,setAssetType] = useState()
AssetTypeService.getAssetTypeById(assettype_assettypeId).then( (res) =>
setAssetType(res.data));
const arrayMap = assetType.map((post)=>{
return(
<ul>
{post.assettypeName}
</ul>
);})
return (
{arrayMap}
);
}
export default GetAssetTypeNameFunction;
... 获取执行错误: 我想是因为我从 eventHandler 中调用了该函数: ...
editAssets(assetsid,assettype_assettypeId){ if (GetAssetTypeNameFunction(assettype_assettypeId) === "Tower") { this.props.history.push(/add-assetstower/${assetsid}/${this.props.match.参数.sitemasterid}); }]
... ----- 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。我正在响应列表中的 onClick 以根据函数 $ 路由到特定组件 我该如何解决这个问题?
【问题讨论】:
-
嗯,=== 同时查看类型和值。
<GetAssetTypeNameComponent datafromparent = {assettype_assettypeId}/>是字符串吗?在我看来,它就像一个组件。 -
@Kevin B GetAssetTypeName 是一个组件。它必须是一个返回字符串才能正常工作的函数吗?我想,因为它在渲染时显示了一个字符串,所以组件将返回一个字符串。错了吗?
-
嗯,条件不会调用左侧的内容,它只是说,它们是否相同。在这种情况下,它们不是。
标签: reactjs string function if-statement