简体   繁体   English

反应动态组件不渲染

[英]React dynamic component not rendering

I have this function that generates dynamic components based on an API我有这个 function 生成基于 API 的动态组件


const renderWork = () =>{
  let DOM = []

  fetch('/api/work/')
  .then(res => res.json())
  .then(res => {
    for (let i = 0; i < res.length; i++){
      DOM.push(
        <Item id={res[i]._id}>
          <Item.Image src={res[i].imageURL} />
          <Item.Content>
            <Item.Header as='a'>Watchmen</Item.Header>
            <Item.Meta>
              <span className='cinema'>{res[i].createdDate}</span>
            </Item.Meta>
              <Item.Description>{res[i].description}</Item.Description>
            <Item.Extra>
              <Label>Hi</Label>

              <Button primary floated='right'>
                Buy tickets
                <Icon name='right chevron' />
              </Button>
            </Item.Extra>
          </Item.Content>
        </Item>
      )
    }
  })

  return DOM
}

I am trying to render those items by calling the renderWork() function in the main component我正在尝试通过调用主组件中的renderWork() function 来渲染这些项目

The main Componenet:主要组件:

function Work(){

  return (   
    <div>
      <Nav/> 
      <div style={css.body}>
      <Item.Group divided>
        {renderWork()}
      </Item.Group>

      </div>
    </div>
  )
}

I am not sure why doesn't it render on the page I tried:我不确定为什么它不在我尝试过的页面上呈现:

  • Making the DOM a state and change it.使 DOM 成为 state 并更改它。

  • using the useEffect hook to manage the state and/or the DOM使用useEffect挂钩来管理 state 和/或 DOM

still, the items won't render仍然,这些项目不会呈现

I am using react.semantic-UI for my components我正在为我的组件使用 react.semantic-UI

I would keep api and component rendering separate.我会将 api 和组件渲染分开。

const renderWork = () => {
  return fetch('/api/work/')
    .then(res => res.json())
}
function WorkItem({item}) {
  return <Item id={item._id}>
          <Item.Image src={item.imageURL} />
          <Item.Content>
            <Item.Header as='a'>Watchmen</Item.Header>
            <Item.Meta>
              <span className='cinema'>{item.createdDate}</span>
            </Item.Meta>
              <Item.Description>{item.description}</Item.Description>
            <Item.Extra>
              <Label>Hi</Label>

              <Button primary floated='right'>
                Buy tickets
                <Icon name='right chevron' />
              </Button>
            </Item.Extra>
          </Item.Content>
        </Item>
}
function Work() {
  const [items, setItems] = useState([])

  useEffect(() => {
    renderWork()
      .then(data => {
        setItems(data)
      })
  }, [])

  return (   
    <div>
      <Nav/> 
      <div style={css.body}>
      <Item.Group divided>
        {items.map(item => <WorkItem item={item}/>}
      </Item.Group>

      </div>
    </div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM