簡體   English   中英

反應動態組件不渲染

[英]React dynamic component not rendering

我有這個 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
}

我正在嘗試通過調用主組件中的renderWork() function 來渲染這些項目

主要組件:

function Work(){

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

      </div>
    </div>
  )
}

我不確定為什么它不在我嘗試過的頁面上呈現:

  • 使 DOM 成為 state 並更改它。

  • 使用useEffect掛鈎來管理 state 和/或 DOM

仍然,這些項目不會呈現

我正在為我的組件使用 react.semantic-UI

我會將 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