React.js,内部迭代的正确方法 DOM

React.js, correct way to iterate inside DOM

我是 ReactJS 的新手...

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

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

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

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

正确吗?或者我可以使用具有存储状态的组件和 flux (redux)?

也许更简单更常规的 react 用法可以满足您的要求?

您可以遵循类似于下图所示的模式,以更 "react-like" 的方式实现您的要求:

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>)
  }

}

请注意,这不是完整的代码示例,需要您 "fill in the gaps" 使用当前聊天组件中的其他内容(即设置 this.client

这不是你应该走的路,你不需要对每个项目都使用 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 或其他任何东西。但是,如果你需要打开你的状态很多组件,你可以考虑它。另外,习惯于使用 mapfilter 之类的方法,而不是 for 循环。