【问题标题】:How to pass props on react-redux component?如何在 react-redux 组件上传递道具?
【发布时间】:2022-01-04 08:51:42
【问题描述】:

我的应用程序中未定义道具会引发未定义的错误。 一旦定义了状态,它就不会使用新的 props 重新渲染组件。

  render(){
    // console.log("RENDER PROPS", this.props)
    const  { name, category, price, img} = this.props

    return(
      <div>
        <h2>={name}/>
        <h4>{category}/>
        <h3>{price}</>
        <img={img}/>
      </div>
    )
  }
}

【问题讨论】:

  • 您需要将道具传递给您的组件。从您显示的代码中,您是否/如何执行此操作不是很清楚

标签: javascript components reduce


【解决方案1】:

你应该在组件的内部状态中保存道具,参见示例。

export default function Page({ nameFromProps , ageFromProps }) => {
    const [name , setName] = useState(nameFromProps );
    const [age, setAge] = useState(ageFromProps );
   useEffect(() => {
      setName(nameFromProps);
      setAge(ageFromProps);
   },[nameFromProps]);
  return (<div> Data : {name}{age} </div>)
}

【讨论】:

  • OP使用了render方法,所以组件是类组件而不是函数组件
  • 当然代码是类内组件,但我在功能组件中描述了方法。
【解决方案2】:

不是很清楚你如何将props传递给组件,可能这一步有错误,但你可以使用检查

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

检查你的道具值并强制重新渲染

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2018-08-01
    • 2018-02-03
    • 2018-06-28
    相关资源
    最近更新 更多