【问题标题】:Can I change state in 100 components in one click?我可以一键更改 100 个组件的状态吗?
【发布时间】:2019-02-20 19:36:36
【问题描述】:

我在一页上有 100 个帖子组件。每个都有状态isActive。我在这个页面上也有单独的列表,只有这些帖子的标题。如果我单击列表中的项目,那么我想将 Post 组件的状态更改为 isActive: true,并将其余组件的状态更改为 isActive: false。

我在 Post 组件上拥有 Posts 组件,所以我应该在 Posts 组件中遍历所有 Post 组件并将更改状态设置为 isActive:false 而无需当前单击 Post 组件?

在这种情况下是不是很夸张?它有效率吗?我使用 Redux,所以也许它会有所帮助?

class Posts extends Component {
  state = { 
    isActive: this.props.isActive
  }

  render() {
    return (
      <div>
        {this.props.posts.map((post, index) => 
          <Post isActive={this.state.isActive} key={index} />
        )}
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    posts: state.posts.posts,
    isActive: state.posts.isActive
  }
}

export default connect(mapStateToProps, null)(Posts);

class Post extends Component {
  state = { 
    isActive: this.props.isActive
  }

  onClick = () => {
    this.setState(state => ({
      isActive: !state.isActive
    }));
  }

  render() { 
    return (
      <div className={this.state.isActive ? "show" : ""} onClick={this.onClick}>
        Post
      </div>
    );
  }
}

export default Post;

class List extends Component {

  onClick = () => {
    //here I would like to set isActive:true to current clicked Post and isActive:false to rest of Posts
  }

  render() {
    return (
      <ul>
        {this.props.posts.map((post, index) => 
          <li onClick={this.onClick}>{post.name}</li>
        )}
      </ul>
    );
  }
}

const mapStateToProps = state => {
  return {
    posts: state.posts.posts
  }
}

export default connect(mapStateToProps, null)(List);

【问题讨论】:

  • 如果你没有使用 Redux,我建议将这个 isActive 状态保留在父组件中。但是,您使用的是 Redux。那么为什么不以某种方式更改商店中的状态呢?您的商店和相关州的形状如何?如果你分享这些信息会很好。
  • 假设所有这些组件都基于父状态进行渲染,您只需更改父状态
  • 所以首先我必须将所有组件更改为 isActive:false 并将下一个当前 Post 更改为 isActive:true?
  • 从逻辑上讲,是的。如果您的状态结构足够好,这可以很容易地完成。这就是我问相关代码的原因。不过,这可能会根据您使用此状态的方式和位置而改变。例如,那些不活跃的帖子会在其他地方可见吗?你想通过再次点击这些帖子将isActive 更改为true 吗?因此,如果我们看不到某些代码和您的应用程序结构,我们就无法准确提出任何建议。
  • @devserkan 我更新了我的问题。谢谢!

标签: javascript reactjs redux


【解决方案1】:

你可以只存储 selectedID(或索引)并使用简单的条件,像这样:

class Posts extends Component {

  render() {
    return (
      <div>
        {this.props.posts.map((post, index) => 
          <Post isActive={this.props.selectedIDX === index} post={post} />
        )}
      </div>
    );
  }
}    

// connect with posts and selectedIDX 


class List extends Component {
  constructor (props) {
    super(props)
    this.onClickHandler = this.onClickHandler.bind(this);
  }

  onClickHandler = (id) => {
    this.props.actionToSetSelectedIDX( id );
  }

  render() {
    return (
      <ul>
        {this.props.posts.map((post, index) => 
          <li onClick={(e, index) => this.onClickHandler(index) }>{post.name}</li>
        )}
      </ul>
    );
  }

 // connect with posts, selectedIDX and actionToSetSelectedIDX

【讨论】:

    【解决方案2】:

    这是一个仅在一个文件中的简单应用程序 :) 您可以阅读 cmets 并尝试了解发生了什么。它将让您了解如何在商店中保留status 状态、调度操作和更新您的状态。

    如您所见,Post 和 List 组件没有任何状态。它们只是愚蠢的组件。父组件Posts 渲染它们。

    您可以看到一个工作示例here,fork 并播放它。此示例有单独的目录和文件。我只是将所有内容放在一个文件中以将其正确移动到此处。我不能保证将沙盒保存太久,所以你可能想立即分叉它:)

    PS:这是一个午夜的乐趣。它可能不包括最佳实践:)

    import React from "react";
    import ReactDOM from "react-dom";
    import { Provider, connect } from "react-redux";
    import { createStore, combineReducers } from "redux";
    
    // To use styles in a single file. You can use a .css file to define those
    // and use className instead of styles in the Post component
    
    const styles = {
      post: { border: "1px solid gray", marginTop: "-1px" },
      show: { backgroundColor: "silver"}, 
    }
    
    // Posts is the parent component. It renders Post and List component by
    // mapping the posts.
    
    class Posts extends React.Component {
      // This method changes the status state by passing a post to
      // the action creator
    
      handleStatus = post => this.props.changeStatus(post);
    
      // This method maps the posts and renders Post components for each post.
      // We are passing the post and isActive boolean.
    
      getPosts() {
        return this.props.posts.map(post => {
          // We are getting the isActive by checking the status state
          // if it has our post's id.
          const isActive = this.props.status[post.id];
          return <Post key={post.id} post={post} isActive={isActive} />;
        });
      }
    
      // This method renders our List items, li's. Again, we are passing the
      // post and our handleStatus method to change the status.
    
      getList() {
        return this.props.posts.map(post => (
          <List key={post.id} post={post} handleStatus={this.handleStatus} />
        ));
      }
    
      render() {
        return (
          <div>
            {this.getPosts()}
            <ul>{this.getList()}</ul>
          </div>
        );
      }
    }
    
    // Post is a stateless, dumb component. It just renders the post item.
    
    const Post = props => {
      const { id, title } = props.post;
      const { isActive } = props;
    
      // We check the isActive and if it is true then add a show class.
    
      let classes = styles.post;
      if (isActive) {
        classes = { ...classes, ...styles.show };
      }
    
      return (
        <div style={classes}>
          <p>ID: {id} </p>
          <p>Title: {title}</p>
        </div>
      );
    };
    
    // List is a stateless, dumb component just renders li's. But, it has
    // handleStatus prop. By onClick and using another method, we are
    // passing our post back to the parent, to the handleStatus method
    
    const List = props => {
      const { post, handleStatus } = props;
      const changeStatus = () => handleStatus(post);
      return <li onClick={changeStatus}>{post.title}</li>;
    };
    
    // We open our state to our component.
    
    const mapStateToProps = state => ({
      posts: state.posts.posts,
      status: state.posts.status,
    });
    
    // This is our action creator, takes the post as parameter and
    // use it as the payload.
    
    const changeStatus = post => ({
      type: types.CHANGE_STATUS,
      post,
    });
    
    // Connecting our component.
    
    const ConnectedPosts = connect(
      mapStateToProps,
      { changeStatus },
    )(Posts);
    
    // Just defining our action creator types, avoiding magic strings.   
    
    const types = {
      CHANGE_STATUS: "CHANGE_STATUS",
    };
    
    // This is our reducer. We have one posts property and one status in our state.
    
    const initialState = {
      posts: [
        { id: "1", title: "foo" },
        { id: "2", title: "bar" },
        { id: "3", title: "baz" },
      ],
      status: {},
    };
    
    // Our reducer takes the post and adds post's id in our status state.
    // In the initial state they are all undefined, so not true. In the first
    // click, we change to true for each post. If we click again, we change it to
    // false without mutating our original state.
    
    const posts = (state = initialState, action) => {
      switch (action.type) {
        case types.CHANGE_STATUS: {
          const {
            post: { id },
          } = action;
          const newStatus = { ...state.status, [id]: !state.status[id] };
          return { ...state, status: newStatus };
        }
        default:
          return state;
      }
    };
    
    // Our store.    
    
    const rootReducer = combineReducers({
      posts,
    });
    
    const store = createStore(rootReducer);
    
    // Rendering our app.
    
    const rootElement = document.getElementById("root");
    
    ReactDOM.render(
      <Provider store={store}>
        <ConnectedPosts />
      </Provider>,
      rootElement,
    );
    

    【讨论】:

    • 这个reducer将允许open许多帖子和close所有帖子——当点击已经活跃的项目时。 const newStatus = { {}, [id]: true }; - 会给你一种“手风琴风格” - 允许 open 和 change(关闭其余部分)但不允许 close。
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2019-10-16
    • 2020-07-16
    • 2015-01-10
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多