簡體   English   中英

基於 state 在 React JS 中有條件地渲染內容

[英]Rendering Content Conditionally in React JS Based on the state

我有一個頁面呈現已發布的問題。 我想創建一個按鈕,僅顯示基於 state = {isAnswered: true} 的已回答問題。

如果 state isAnswered 為真,那么 onClick 將僅在 object 中 isAnswered 設置為真時顯示已回答的問題。

我如何使用此過濾器按鈕根據它們的 state 有條件地渲染它們。

function 是否應該存儲為在渲染 function 或之前調用的常量?

this.state.posts 是后端這些對象的數組:

在此處輸入圖像描述

這是我嘗試過的。

class Posts extends Component {
    state = {
        posts: []
    }
 
    render () {
        let posts = <p style={{ textAlign: 'center' }}>Something went wrong!</p>;
        

        let {isAnswered} = this.state;

        const renderAuthButton = () => {
          if (isAnswered === true) {
            if ( !this.state.error ) {
            
                posts = this.state.posts.map( (post) => {
                    return (
                        
                        <Post
                            key={post.key}
                            id={post.key}
                            title={post.title}
                            type={post.type}
                            body={post.body}
                            answer={post.answer}
                            onChange={(value, id) => this.postAnswerHandler(value,id)}
                            clicked={(body) => this.displayAnswerHandler(body)}
                           
                             />
                            
                        
                    );
                } );
            }
          } 
        }
      }

        return ( 
            <button onClick={renderAuthButton()}>Filter</button>
                 {posts} 
               )

您誤解了您的數據結構。 this.state有一個屬性this.state.posts是一個數組。 數組中的每個元素都是一個 object ,具有多個屬性,包括isAnswered

當你這樣做時:

let {isAnswered} = this.state;

您正在尋找不存在的屬性this.state.isAnswered 沒有頂級isAnswered屬性。 它存在於每個post object 中,並且每個帖子都不同。 因此,您需要查看循環內部isAnswered

老實說,這里有很多奇怪和倒退的地方。 不要在render()內部創建回調! 不要從回調中返回 JSX!

這是我清理它的嘗試。 我正在向this.state添加一個屬性,它告訴我們是否過濾帖子。 單擊button更改this.state.isFiltered render function 根據當前 state 進行適當渲染。

class Posts extends Component {
  state = {
    posts: [],
    isFiltered: false,
    isError: false
  };

  async componentDidMount() {
    // do your API fetch and set the state for `posts` and `isError`
    try {
      const fetchedPosts = someApiFunction();
      this.setState({
        posts: fetchedPosts
      });
    } catch (error) {
      this.setState({
        isError: true
      });
    }
  }

  onClickFilter = () => {
    // toggles filter on and off
    this.setState((prevState) => ({
      isFiltered: !prevState.isFiltered
    }));
  };

  render() {
    if (this.state.isError) {
      return <p style={{ textAlign: "center" }}>Something went wrong!</p>;
    }

    // show only answered posts if isFiltered is true, or all posts if false
    const visiblePosts = this.state.isFiltered
      ? this.state.posts.filter((post) => post.isAnswered)
      : this.state.posts;

    return (
      <>
        <button onClick={this.onClickFilter}>Filter</button>
        {visiblePosts.map((post) => {
          return (
            <Post
              key={post.key}
              id={post.key}
              title={post.title}
              type={post.type}
              body={post.body}
              answer={post.answer}
              onChange={(value, id) => this.postAnswerHandler(value, id)}
              clicked={(body) => this.displayAnswerHandler(body)}
            />
          );
        })}
      </>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM