无法设定多张图片

时间:2019-04-25 08:16:51

标签: javascript reactjs

我正在从后端获取缓冲的图像/ jpeg。每次收到新图像并将其传递给子组件时,父组件都会执行setState。

子组件会收到每个更新,并且可以在控制台日志中看到,但是它仅显示单个图像。

父组件:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      nodeResponse: ''
  }
}

getFileStatusFromNode = (data) => {
    this.setState({nodeResponse: data})
  }

render() {

let CardView = nodeResponse !== '' &&
  <Card key={nodeResponse.fileName} name={nodeResponse.fileName} image={nodeResponse.buffer} />


return (
      <div className="App tc">
         { CardView }
      </div>
     )
   }
}

子组件:

class Card extends PureComponent {
  constructor({props}) {
    super(props);
    this.state = { 
      src: '',
    };
}

componentDidMount() {
  console.log("Card mounted")
    this.setState(prevState => ({
        src: [this.props.image, ...prevState.src]
      }), () => console.log(this.state.src, this.props.name));
}

render() {
  const { name } = this.props;
  const { src } = this.state;

 return (

      <a style={{width: 200, height: 250}} key={name} className={'tc'} >
      <div id='images'>
      <img style={{width: 175, height: 175}} className='tc' alt='missing' src={`data:image/jpeg;base64, ${src}`}/>
      </div>
      </a> 
    )
  }
}

注意::这些图像来自套接字io。我想实时显示它们,而不是先创建列表然后一起显示。

2 个答案:

答案 0 :(得分:0)

在定义<Card>组件时,您仅渲染1 <CardView>

假设nodeResponse.imageFiles是一个文件数组,则应具有以下内容:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      nodeResponse: ''
  }
}

getFileStatusFromNode = (data) => {
    this.setState({nodeResponse: data})
  }

render() {

let CardView

if(this.state.nodeResponse !== '') {
  CardView = this.state.nodeResponse.imageFiles.map(file => (
     <Card
       key={image.fileName}
       name={image.fileName}
       image={image.buffer} />
  )
)}

return (
      <div className="App tc">
         { CardView }
      </div>
     )
   }
}

答案 1 :(得分:0)

尝试

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      nodeResponse: []
    }
  }

  getFileStatusFromNode = (data) => {
    // here you merge the previous data with the new
    const nodeResponse = [...this.state.nodeResponse, data];
    this.setState({ nodeResponse: nodeResponse });
  }

  render() {
   return (<div className="App tc">
      {this.state.nodeResponse.map(n => <Card key={n.fileName} name={n.fileName} image={n.buffer} />)}
   </div>);
  }
}

以及您的子组件中

class Card extends PureComponent {
  render() {
    const { src } = this.props;

   return (<a style={{width: 200, height: 250}} className="tc">
      <div id='images'>
        <img style={{width: 175, height: 175}} className='tc' alt='missing' src={`data:image/jpeg;base64, ${src}`}/>
      </div>
    </a>);
  }
}