简体   繁体   English

为什么将React组件存储为变量或状态是错误的设计实践

[英]Why React Components being stored as variables or as state is bad design practice

My application makes an API call and turns each element of a JSON array into a React Component. 我的应用程序进行API调用,并将JSON数组的每个元素转换为React组件。

I made an array of these child components, but they do not render. 我制作了这些子组件的数组,但未渲染。 How do I force them to render? 如何强迫他们渲染? Should I use the React.create() and then call render() on each? 我应该使用React.create()然后在每个对象上调用render()吗?

What is the proper vanilla React design pattern for this? 正确的Vanilla React设计模式是什么?

var apiPosts = [];

class PostsItsContainer extends Component {
 constructor(props){
 super(props);
 this.state = {}
 }

componentDidMount(){
   let uri = "some_API_endpoint" ; 

   if(uri){ 
    fetch(uri)
   .then(data => data.json())
   .then(posts => {
     posts.data.children.forEach(post => {
       let imgUrl = post.data.hasOwnProperty('preview') ? post.data.preview.images[0].source.url : null;
       let postData = [post.data.title, imgUrl, post.data.link];
       apiPosts.push(<PostIt link={post.data.url} image={imgUrl} title={post.data.title} />);
     });
   }).catch(err => console.log(err)) }

 }

 render() {
   return (
     <div className="PostsItsContainer">
      {apiPosts}
     </div>
   );
 }
}

EDIT: 编辑:

I changed my title cause it was pretty generic. 我更改了标题,因为它非常通用。 And really I was asking why my method was bad design practice and wouldn't give me proper results. 真的,我是在问为什么我的方法是不良的设计实践,而不会给我适当的结果。

@Jayce444 told me why and @Supra28 gave a good answer. @ Jayce444告诉我为什么,@ Supra28给出了很好的答案。 I'm posting @Jayce444's comment here for it to be easily read: 我在这里发布@ Jayce444的评论,以便于阅读:

It's perfectly possible to store a component in a variable or array and then use that. 完全有可能将组件存储在变量或数组中,然后使用它。 But the store/props should be reserved for the bare bones data needed to render stuff, not the entire pre-made component. 但是商店/道具应该保留用于渲染东西所需的裸露数据,而不是整个预制组件。 There's s few reasons, two being: firstly you'll bloat the state/props doing that, and secondly you're combining the logic and view functionalities. 原因有几个,其中两个是:首先,您会膨胀这样做的状态/道具,其次,您将逻辑和视图功能结合在一起。 The data needed to render a component and the actual way it's rendered should be loosely coupled, makes your components easier to maintain, modify and understand. 呈现组件所需的数据及其呈现的实际方式应松散耦合,使您的组件更易于维护,修改和理解。 It's like separating HTML and CSS into separate files, it's easier :) 就像将HTML和CSS分离到单独的文件中一样,这更容易:)

So what we do here is : 所以我们在这里做的是:

1) Set the loading state to true initially 1)最初将加载状态设置为true

2) When we get the data from the api we want our component to rerender to display the new data, so we keep the data in the state. 2)当我们从api获取数据时,我们希望组件重新呈现以显示新数据,因此我们将数据保持在该状态。

3) Inside of the render function we return a Loding indicator if our loading indicator is true or return the array of posts (map returns an array) wrapped with a div. 3)如果加载指标为true,则在render函数内部返回Loding指标,或者返回以div包裹的帖子数组(map返回数组)。

class PostsItsContainer extends Component {
  constructor(props) {
    super(props)
    this.state = { apiData: [], loadingPosts: true } // Loading state to know that we are loading the data from the api and do not have it yet so we can display a loading indicator and don't break our code
  }

  componentDidMount() {
    let uri = "some_API_endpoint"
    if (uri) {
      fetch(uri)
        .then(data => data.json())
        .then(posts => {
          this.setState({ apiData: posts.data.children, loadingPosts: false }) //Now we save all the data we get to the state and set loading to false; This will also cause the render function to fire again so we can display the new data
        })
        .catch(err => console.log(err))
    }
  }

  render() {
    if (this.state.loadingPosts) return <div>Loading......</div> //If we haven't recieved the data yet we display loading indicator
    return (
      <div className="PostsItsContainer">
        {this.state.postData.map((post, i) => (
          <PostIt
            key={i} //You'll need a key prop to tell react this is a unique component use post.id if you have one
            link={post.data.url}
            image={
              post.data.preview ? post.data.preview.images[0].source.url : null
            }
            title={post.data.title}
          />
        ))}
      </div>
    )
  }
}

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

相关问题 React-在表单组件中使用状态的最佳实践? - React - Best practice with state in form components? 在 React 组件中,在渲染/返回之外引用子组件是“坏习惯”吗? - In React components, is it “bad practice” to refer to child components outside of the render/return? 为什么全局变量被认为是不好的做法? - Why are global variables considered bad practice? React Hooks:为什么将设置状态函数传递给子组件是不好的做法? - React Hooks : Why is it bad practice to pass the set state funcitons to a Child Component? 只在子组件中使用 props 是不好的做法吗? 没有自己状态的子组件 - Is it bad practice to only use props in child components? Child components without own state 在React解包“this”是不好的做法吗? - Is it bad practice to unpack “this” in React? 为什么存储在 firestore 中的数据没有被 react 获取? - Why is the data stored in firestore not being fetched in react? 为什么在 componentDidUpdate 中使用 setState 在 React 中被视为不好的做法? - Why is using setState inside componentDidUpdate seen as a bad practice in React? 反应状态与道具-为什么状态更改未反映在组件中? - React State vs. Props - Why are state changes not reflected in components? 将 state 变量和方法传递给 React 中的子组件的更简洁方法? - Cleaner way to pass state variables and methods to child components in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM