javascript - React Native - 每次当 child 设置状态时渲染更新(我不想)

标签 javascript reactjs react-native render setstate

我有一个包含不同组件的 page.js,这些组件在 componentDidMount() 中设置状态。每次都执行父级的渲染(总共 10 个)。但这是一个问题,因为我想在 componentDidUpdate 上对 api rest 执行请求,并且这个函数执行了很多次。

有什么办法可以让子进程的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>
        )
    }
}

最佳答案

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

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

关于javascript - React Native - 每次当 child 设置状态时渲染更新(我不想),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53315368/

相关文章:

javascript - Cardlist 未定义 no-undef

javascript - 即使函数不返回任何内容,onBeforeUnload 也会创建提示

javascript - Angular : How to edit $scope from the console?

javascript - Modernizr 检查 css3d 转换和 flexbox 包括 ie10

reactjs - react 谷歌地图 : Can't get bounds

javascript - 使用日期对象格式化数组并在下拉列表中显示它们

reactjs - Firebase React Native——如何获取和传输设备 ID/ token ?

react-native - react native 警告 : RCTC module not exported

ios - 类型错误 : undefined is not an object (evaluating '_rxjs.queueScheduler.constructor' )

javascript - 为什么这个 javascript 和 html 代码没有计算结果?