简体   繁体   中英

Child component not updating after array prop updated

When updating an array (inside an object), by adding an object to it, the child component is not re-rendered. The parent component is, however.

I tried updating a non-array property of the object, while also updating the array property of the object, the child component will then update. Eg:

Does not work:

obj.arr.push(user);

Works:

obj.arr.push(user);
obj.test = "wow";

My problem exists with the users prop, passed to the Users component from the Lobby component. When a user joins, the socket event lobby_player_joined is triggered, modifying the users array.

Lobby component (parent):

...

const StyledTabs = styled(Tabs)`${TabsStyle};`;

class Lobby extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tab: 0,
    };
    this.props.setTitle('Lobby');
  }

  static get propTypes() {
    return {
      history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired,
      location: PropTypes.shape({ state: PropTypes.object }).isRequired,
      setTitle: PropTypes.func.isRequired,
      initializeSocket: PropTypes.func.isRequired,
      onceSocketMessage: PropTypes.func.isRequired,
      onSocketMessage: PropTypes.func.isRequired,
      sendSocketMessage: PropTypes.func.isRequired,
    };
  }

  async componentDidMount() {
    await this.props.initializeSocket((error) => {
      console.error(error);
    });

    await this.props.onSocketMessage('exception', (error) => {
      console.log(error);
    });

    await this.props.onceSocketMessage('lobby_joined', (lobby) => {
      this.setState({ lobby });
    });

    await this.props.sendSocketMessage('lobby_join', {
      id: this.props.location.state.id,
      password: this.props.location.state.password,
    });

    await this.props.onSocketMessage('lobby_player_joined', (user) => {
      const { lobby } = this.state;
      lobby.users.push(user);
      return this.setState({ lobby });
    });

    await this.props.onSocketMessage('lobby_player_left', (user) => {
      const { lobby } = this.state;
      const userIndex = lobby.users.findIndex(u => u.id === user.id);
      if (userIndex !== -1) {
        lobby.users.splice(userIndex, 1);
        this.setState({ lobby });
      }
    });

    await this.props.onSocketMessage('lobby_new_host', (host) => {
      const { lobby } = this.state;
      lobby.host = host;
      return this.setState({ lobby });
    });
  }

  handleTab = (event, value) => {
    console.log(this.state.lobby);
    this.setState({ tab: value });
  };

  handleSwipe = (value) => {
    this.setState({ tab: value });
  };

  render() {
    if (!this.state.lobby) {
      return (<div> Loading... </div>);
    }

    return (
      <Container>
        <AppBar position="static">
          <StyledTabs
            classes={{
              indicator: 'indicator-color',
            }}
            value={this.state.tab}
            onChange={this.handleTab}
            fullWidth
            centered
          >
            <Tab label="Users" />
            <Tab label="Info" />
          </StyledTabs>
        </AppBar>
        <SwipeableViews
          style={{ height: 'calc(100% - 48px)' }}
          containerStyle={{ height: '100%' }}
          index={this.state.tab}
          onChangeIndex={this.handleSwipe}
        >
          <TabContainer>
            <Users
              {...this.state.lobby}
            />
          </TabContainer>
          <TabContainer>
            <Info
              {...this.state.lobby}
            />
          </TabContainer>
        </SwipeableViews>
      </Container>
    );
  }
}

...

Users component (child):

...

class Users extends Component {
  state = {
    isReady: false,
    usersReady: [],
  };

  async componentDidMount() {
    await this.props.onSocketMessage('lobby_user_ready', (data) => {
      this.setState(prevState => ({
        usersReady: [...prevState.usersReady, data.socketId],
      }));
    });

    await this.props.onSocketMessage('lobby_user_unready', (data) => {
      this.setState(prevState => ({
        usersReady: prevState.usersReady.filter(id => id !== data.socketId),
      }));
    });
  }

  componentWillUnmount() {
    this.props.offSocketMessage('lobby_user_ready');
    this.props.offSocketMessage('lobby_user_unready');
  }

  static get propTypes() {
    return {
      id: PropTypes.number.isRequired,
      users: PropTypes.arrayOf(PropTypes.object).isRequired,
      userCount: PropTypes.number.isRequired,
      host: PropTypes.shape({
        username: PropTypes.string.isRequired,
      }).isRequired,
      sendSocketMessage: PropTypes.func.isRequired,
      onSocketMessage: PropTypes.func.isRequired,
      offSocketMessage: PropTypes.func.isRequired,
    };
  }

  readyChange = () => {
    this.setState(prevState => ({ isReady: !prevState.isReady }), () => {
      if (this.state.isReady) {
        return this.props.sendSocketMessage('lobby_user_ready', { id: this.props.id });
      }
      return this.props.sendSocketMessage('lobby_user_unready', { id: this.props.id });
    });
  };

  renderStar = (user) => {
    const { host } = this.props;
    if (host.username === user.username) {
      return (<Icon>star</Icon>);
    }
    return null;
  }

  render() {
    return (
      <UserContainer>
        { this.props.users.length }
        <CardsContainer>
          {this.props.users.map(user => (
            <UserBlock
              className={this.state.usersReady.includes(user.socketId) ? 'flipped' : ''}
              key={user.socketId}
            >
              <BlockContent className="face front">
                { this.renderStar(user) }
                <div>{user.username}</div>
                <Icon className="icon">
                  close
                </Icon>
              </BlockContent>
              <BlockContent className="face back">
                <Icon>
                  star
                </Icon>
                <div>{user.username}</div>
                <Icon className="icon">
                  check
                </Icon>
              </BlockContent>
            </UserBlock>
          ))}
        </CardsContainer>
        <InfoContainer>
          <p>Players</p>
          <p>
            {this.props.users.length}
            {' / '}
            {this.props.userCount}
          </p>
          <p>Ready</p>
          <p>
            {this.state.usersReady.length}
            {' / '}
            {this.props.userCount}
          </p>
        </InfoContainer>
        <StyledButton
          variant={this.state.isReady ? 'outlined' : 'contained'}
          color="primary"
          onClick={this.readyChange}
        >
          { this.state.isReady ? 'Unready' : 'ready'}
        </StyledButton>
      </UserContainer>
    );
  }
}

...

Could anyone help me out with making the Users component update/re-render when modifying the array prop?

Don't mutate the state. Use something like this

await this.props.onSocketMessage('lobby_player_joined', (user) => {
  const { lobby } = this.state;
  return this.setState({ lobby : {...lobby, users: lobby.users.concat(user)} });
});

edit: fixed missing bracket

This is because React compares props for equality to determine whether to re-render a component. Instead of

obj.arr.push(user);

Try

const newObj = {...obj, arr: obj.arr.concat(user)};

which creates a new Object.

An alternative is using Immutable.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM