我已经生成了一个功能组件,以使父组件可读且结构更好。
以下内容不起作用,即:尽管console.log打印显示所需的值,但该条件永远不成立。
const UpdateIcons = ({products, move2Program, onSaveTable}) => {
//the condition never fires even if console.log shows A, B, C as expected
if (products['intake_mgr_decision'] === 'A'
&& products['intake_family_decision'] === 'B'
&& products['intake_status'] === 'C')
return <button type="button" className="btn btn-success pull-left"
onClick={move2Program}>JOIN</button>
return <button type="button" className="btn btn-success pull-left"
onClick={onSaveTable}>UPDATE</button>
}
添加局部变量解决了该问题。
我的问题是为什么?有什么解释?
以下作品
const UpdateIcons = ({products, move2Program, onSaveTable}) => {
let mgr_decision = products['intake_mgr_decision']
let family_decision = products['intake_family_decision']
let status = products['intake_status']
if (mgr_decision === 'A' && family_decision === 'B' && status === 'C')
return <button type="button" className="btn btn-success pull-left"
onClick={move2Program}>JOIN</button>
return <button type="button" className="btn btn-success pull-left"
onClick={onSaveTable}>UPDATE</button>
}
事实是,您必须在返回带有参数的元素的函数和返回带有道具的元素的函数之间找到一个小的分析。
考虑以下示例:
//here is the difference, when you use function, function takes arguments as it is.
const UpdateIcons = (products) => {
// if you use this as component props will be like products props will return the products object again, here you have to use {products} destructuring or products.propducts["One"]
//like this const UpdateIcons = ({products}) => {
if((products["One"] === "A") && (products["Two"] === "B") && (products["Three"] === "C") ) {
return <p>Conditional</p>
}
return <p>Show Always</p>
}
class MyIssue extends Component {
render() {
const { products } = this.props;
return (
<div>
{UpdateIcons(products)}
{/*passing arguments here products will be {"One": "A", "Two": "B"}*/}
<UpdateIcons products={products} />
{/* passing props , props will be same as products */}
</div>)
}
}
class App extends Component {
constructor() {
super();
this.state = {
products: {
"One": "A",
"Two": "B",
"Three": "C"
}
};
}
render() {
return <MyIssue products={this.state.products} />
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句