1

在我的 React 应用程序中,我正在使用功能组件开发一个屏幕。我想用模拟数据填充屏幕上的数据,直到我的 API 准备好。我基本上有一个打开状态的手风琴,我想在其中显示名称。现在,我正在硬编码名称来填充它。稍后,我将替换为来自 Store 的实际数据。所以要做到这一点,我在我的组件本身中定义如下的硬编码数据,因为在 API 准备好之后,我的道具将拥有所有必需的数据。

function MyComponent (props) {
    props={
        history: {},
        data:[
          {
            name:’XYZ’,
          },
          {
            name:’ABC’,
          }
        ]
    }

    return (
       <div>Content goes here </div>
     )
}

这引发了我的错误。我想了解我是否正确执行此操作,因为我需要读取 div 中的数据值。

4

3 回答 3

1

道具是不可变的,所以你不应该改变它们。相反,您可以模拟您传递给的道具MyComponent


示例:在父组件中:

function MyApp() {
  const mockProps={
    history: {},
    data:[
      name:’XYZ’,
    ]
  }

  return <MyComponent {...mockProps}/>
}

并且在MyComponent

function MyComponent (props) {
 // do something with props here
 return <div>Content goes here </div>
}
于 2019-11-29T13:41:48.700 回答
1

最好将这些数据模拟为来自父容器,这样当您稍后添加 Redux 库时,您可以简单地更改 /where/ props are being sent from。

例如

在父 JS 中:

const Parent = props => {
const [accordionData, setData] = useState(['#1', '#2', '#3'])

/ ... rest of component / 

return <Accordion accordionData={accordionData} />

}  

const Accordion = props => {

    const { accordionData } = props // pull props from parent component.

    const mapAccordionData = accordionData.map(el => { return <div key={el}>el</div> })

    return mapAccordionData

}

像这样的东西应该工作。

ParentJS 通过 parent->child props 为手风琴提供数据数组。稍后这将是 store->child 道具。Accordion (child) 然后将该数据呈现给用户,以便用户可以通过 div 看到它。

于 2019-11-30T19:39:19.637 回答
0

您可以将道具传递给组件。它们应该来自父组件状态或存储(如 Redux 存储)。

function MyComponent(props) {
  return <div>{props.hello}</div>;
}


class ParentComponent extends React.Component {
  state = {
    hello: 'Hello World!',
  }

  render() {
    return <MyComponent hello={this.state.hello} />;
  }
}

您还可以传递一个函数来更改父级的状态,从而使道具也发生变化MyComponent。它不会改变它们,而是返回一个新状态并因此传递一组新的道具。如果您需要任何进一步的解释,请告诉我。

于 2019-11-29T14:16:12.993 回答