2

我是 ReactJS 的新手...

我有一个具有以下类组件结构的项目:

index.js
  --app
    --chat
  --header
  --left
  --right

在 chat.js 组件中,我使用 api 进行谷歌搜索以根据特定关键字检索图像......我的直观解决方案是:

this.client.search("cars")
                .then(images => {
                    for(let el of images) {
                    ReactDOM.render(<img src="{{el.url}}" syle="{{width: '100%'}}" />, document.querySelector('#gimages'));
                    }
                });

它是正确的?或者我可以使用带有通量(redux)的存储状态的组件?

4

2 回答 2

1

也许更简单更传统的 react 使用可以满足您的要求?

您可以遵循类似于下图所示的模式,以更“类似反应”的方式实现您的要求:

class Chat extends React.Component {

  constructor(props) {
    super(props)
    this.state = { images : [] } // Set the inital state and state
                                 // model of YourComponent
  }

  componentDidMount() {

    // Assume "client" has been setup already, in your component

    this.client.search("cars")
    .then(images => {

      // When a search query returns images, store those in the
      // YourComponent state. This will trigger react to re-render 
      // the component
      this.setState({ images : images })
    });
  }

  render() {

    const { images } = this.state

    // Render images out based on current state (ie either empty list, 
    // no images, or populated list to  show images)
    return (<div>
        { 
          images.map(image => {
              return <img src={image.url} style="width:100%" />
          })
        }
    </div>)
  }

}

请注意,这不是一个完整的代码示例,需要您使用当前聊天组件中的其他内容“填补空白”(即设置this.client

于 2018-08-19T23:30:12.810 回答
1

这不是你应该走的路,你不需要ReactDOM.render为每个项目使用。实际上,您根本不需要使用ReactDOM.render。在您的组件中,您可以使用生命周期方法来获取数据,然后将其设置为本地状态。获取数据后,您可以将其传递给单个组件或直接在您的render方法中呈现。

class Chat extends React.Component {
  state = {
    images: [],
  }

  componentDidMount() {
    this.client.search( "cars" )
      .then( images => this.setState( { images } ) );
  }

  renderImages = () =>
      this.state.images.map( image => <Image key={image.id} image={image} /> );

  render() {
    return (
      <div>{this.renderImages()}</div>
    );
  }
}

const Image = props => (
  <div>
    <img src={props.image.url} syle="{{width: '100%'}}" />
  </div>
);

此时,您不需要 Redux 或其他任何东西。但是,如果你需要打开你的状态很多组件,你可以考虑一下。此外,要习惯于使用map,filter而不是 for 循环之类的方法。

于 2018-08-19T23:31:34.420 回答