React Native-每次孩子设置setstate时都会渲染更新(我不想要)

时间:2018-11-15 08:41:50

标签: javascript reactjs react-native render setstate

我有一个page.js,其中包含不同的组件,这些组件在componentDidMount()中使setState生效。父渲染每次执行一次(总共10次)。但这是一个问题,因为我想在基于componentDidUpdate的api上执行api请求,并且此函数执行很多次。

有什么方法可以使孩子中的setstate不影响父对象的呈现?

使用代码更新

  

page.js

import Header from 'Pages/userprofile/general/HeaderMenuUser';
import UserHeader from 'Pages/userprofile/basic/header/UserHeader';
import UserContent from 'Pages/userprofile/basic/content/UserContent';

...

class UserProfile extends Component {

static navigationOptions = ({navigation}) => {

      const user = navigation.getParam('user', '');

      return {
                title: 'User Profile',
                header: (navigation) => <Header {...navigation} title="My profile" user={user} origin="UserProfile" edit={false} />,
                headerTintColor: '#000',
                headerTitleStyle: {
                  fontWeight: 'bold',
                },
            };

  };

  getProfile(){
    //const { user } = this.props.navigation.state.params;

    //Profile.get(user.id).then( response => {
    ProfileApi.get().then( response => {
      this.setState({ user: response.user });
      this.props.navigation.setParams({
        user: response.user,
      });
    });
  }

  render() {
    //console.warn(this.props.isFocused ? 'Focused' : 'Not focused');
    return (
      <ScrollView style={[styles.scroll, globalStyles.generalScrollContainer]}>
            <View style={{backgroundColor:'#fff', minHeight: 50}}>

          <GradientBackground />
              <UserHeader user={this.state.user} edit={false}/>

            </View>
        { typeof this.state.user === "object" && (
          <View style={styles.container}>
            <UserContent user={this.state.user} />
          </View>
        )}

      </ScrollView>
    );
  }
}

export default withNavigationFocus(UserProfile);
  

UserContent.js

export default class UserContent extends Component {

    updateState = (update) => {

      if (update['simple']){
        this.setState({ [update['key']]: update['value'] });
      } else {

        projects = this.state.user.projects;

        projects.push(update['value']);


        this.setState( prevState => ({
          user: {
              ...prevState.user,
              projects: projects
          }
        }));

        this.setState( prevState => ({
          user: {
              ...prevState.user,
              can_create_projects: update['value'].can_create_projects
          }
        }));

        Functions.storeItem('user', this.state.user);

      }

    };

    componentDidMount() {
      Functions.getApiToken().then((response) => {
          this.setState({ url: url + response });
      });

    }

    render() {

        return (
            <View>
              <View style={styles.content}>
                <UserBiography user={this.state.user} />

                <View style={[globalStyles.rowBetween, globalStyles.rowVerticalCenter]}>
                  <Text style={globalStyles.titleText}>Projects</Text>
                  { this.state.user.can_create_projects && (
                  <View>
                    <TouchableOpacity
                      style={styles.button}
                      onPress={() => { this.setState({collapsed: !this.state.collapsed}) }}>
                      <Text style={[globalStyles.textTag, this.state.collapsed ? globalStyles.backgroundBlue : globalStyles.backgroundGary ]}>{this.state.collapsed ? "Add" : "Close add"} project</Text>
                    </TouchableOpacity>
                  </View>
                  ) }
                </View>

                <View style={[globalStyles.borderBottomView, {marginBottom: 30}]}></View>

                <UserCreateProject collapsed={this.state.collapsed} updateState={this.updateState}/>

                {typeof this.state.user === 'object' && this.state.user.projects.length > 0 && (this.state.user.projects.map((project, index) => {
                    return (<UserProject project={project} key={project.id} updateState={this.updateState} />)
                }))}

              </View>

            </View>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用shouldComponentUpdate()方法来控制渲染:

shouldComponentUpdate(nextProps, nextState) {
    if (nextState.render_screen) {
        return true;
    } else {
        return false;
    }
}