React中的无限渲染

iRo*_*tia 6 javascript reactjs react-native

我有问题弄清楚为什么我的应用程序正在做无休止的渲染.

在Inside,我的有状态组件,我在componentDidMount方法中调用redux动作(调用componentWillMount也做无穷无尽的渲染)

class cryptoTicker extends PureComponent {
  componentDidMount() {
    this.props.fetchCoin()
    // This fetches some 1600 crypto coins data,Redux action link for the same in end
  }

  render() {
    return (
      <ScrollView>
        <Header />
        <View>
          <FlatList
            data={this.state.searchCoin ? this.displaySearchCrypto : this.props.cryptoLoaded}
            style={{ flex: 1 }}
            extraData={[this.displaySearchCrypto, this.props.cryptoLoaded]}
            keyExtractor={item => item.short}
            initialNumToRender={50}
            windowSize={21}
            removeClippedSubviews={true}
            renderItem={({ item, index }) => (
              <CoinCard
                key={item["short"]}
              />
            )} 
          />
        </View>
      </ScrollView>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

在CoinCard中我除此之外什么都不做(在Flat列表中注意CoinCard)

class CoinCard extends Component {
  render () { 
    console.log("Inside rende here")
    return (
        <View> <Text> Text </Text>  </View>
    )  
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我控制登录我的重合渲染时,我可以在这里看到Inside rende的无限日志

[问题:]任何人都可以帮我弄清楚为什么会发生这种情况?

您可以单击此处查看我的操作,然后单击此处查看我的减速机.

[更新:]如果您想自己克隆并查看,我的存储库就在这里.

[更新:2]:我已经在github上推送了上面的共享代码,它仍然会记录无尽的console.log语句(如果你可以克隆,运行并回到这个提交).

[更新:3]:我也不再使用<ScrollView />,<FlatList />当我的意思是无休止的渲染时,我的意思是它是无尽的(并且不必要地)将相同的道具传递给子组件(<Coincard />),如果我使用PureComponent,它将不会无休止地记录in render () {in componentWillRecieveProps,如果我这样做console.log(nextProps),我可以看到相同的日志一遍又一遍地传递

Ste*_*ane 2

就像 izb 提到的,pb 的根本原因是在纯组件上完成的业务调用,而它刚刚加载。这是因为你的组件做出了业务决策(<=>“我决定什么时候必须在我自己身上展示某些东西”)。在 React 中这不是一个好的实践,当你使用 redux 时更是如此。该组件必须尽可能愚蠢,甚至不决定要做什么以及何时做。

正如我在您的项目中看到的,您没有正确处理组件和容器概念。您的容器中不应该有任何逻辑,因为它应该只是一个愚蠢的纯组件的包装器。像这样:

import { connect, Dispatch } from "react-redux";
import { push, RouterAction, RouterState } from "react-router-redux";
import ApplicationBarComponent from "../components/ApplicationBar";

export function mapStateToProps({ routing }: { routing: RouterState }) {
    return routing;
}

export function mapDispatchToProps(dispatch: Dispatch<RouterAction>) {
    return {
        navigate: (payload: string) => dispatch(push(payload)),
    };
}
const tmp = connect(mapStateToProps, mapDispatchToProps);
export default tmp(ApplicationBarComponent);
Run Code Online (Sandbox Code Playgroud)

以及匹配的组件:

import AppBar from '@material-ui/core/AppBar';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import { StyleRules, Theme, withStyles, WithStyles } from '@material-ui/core/styles';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import AccountCircle from '@material-ui/icons/AccountCircle';
import MenuIcon from '@material-ui/icons/Menu';
import autobind from "autobind-decorator";
import * as React from "react";
import { push, RouterState } from "react-router-redux";

const styles = (theme: Theme): StyleRules => ({
  flex: {
    flex: 1
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
  root: {
    backgroundColor: theme.palette.background.paper,
    flexGrow: 1
  },
});
export interface IProps extends RouterState, WithStyles {
  navigate: typeof push;
}

@autobind
class ApplicationBar extends React.PureComponent<IProps, { anchorEl: HTMLInputElement | undefined }> {
  constructor(props: any) {
    super(props);
    this.state = { anchorEl: undefined };
  }
  public render() {

    const auth = true;
    const { classes } = this.props;
    const menuOpened = !!this.state.anchorEl;
    return (
      <div className={classes.root}>
        <AppBar position="fixed" color="primary">
          <Toolbar>
            <IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
              <MenuIcon />
            </IconButton>
            <Typography variant="title" color="inherit" className={classes.flex}>
              Title
            </Typography>

            <Tabs value={this.getPathName()} onChange={this.handleNavigate} >
              {/* <Tabs value="/"> */}
              <Tab label="Counter 1" value="/counter1" />
              <Tab label="Counter 2" value="/counter2" />
              <Tab label="Register" value="/register" />
              <Tab label="Forecast" value="/forecast" />
            </Tabs>

            {auth && (
              <div>
                <IconButton
                  aria-owns={menuOpened ? 'menu-appbar' : undefined}
                  aria-haspopup="true"
                  onClick={this.handleMenu}
                  color="inherit"
                >
                  <AccountCircle />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={this.state.anchorEl}
                  anchorOrigin={{
                    horizontal: 'right',
                    vertical: 'top',
                  }}
                  transformOrigin={{
                    horizontal: 'right',
                    vertical: 'top',
                  }}
                  open={menuOpened}
                  onClose={this.handleClose}
                >
                  <MenuItem onClick={this.handleClose}>Profile</MenuItem>
                  <MenuItem onClick={this.handleClose}>My account</MenuItem>
                </Menu>
              </div>
            )}
          </Toolbar>
        </AppBar>
      </div >
    );
  }
  private getPathName(): string {
    if (!this.props.location) {
      return "/counter1";
    }
    return (this.props.location as { pathname: string }).pathname;
  }
  private handleNavigate(event: React.ChangeEvent<{}>, value: any) {
    this.props.navigate(value as string);
  }

  private handleMenu(event: React.MouseEvent<HTMLInputElement>) {
    this.setState({ anchorEl: event.currentTarget });
  }

  private handleClose() {
    this.setState({ anchorEl: undefined });
  }
}
export default withStyles(styles)(ApplicationBar);
Run Code Online (Sandbox Code Playgroud)

然后你会告诉我:“但是我在哪里发起可以填充我的列表的呼叫呢?” 好吧,我在这里看到你使用 redux-thunk (我更喜欢 redux observable...学习起来更复杂,但是 waaaaaaaaaaaaaaaaay 更强大),那么这应该是 thunk 来启动这个调度!

总结一下:

  • 组件:最愚蠢的元素,通常应该只有渲染方法,以及一些其他方法处理程序来冒泡用户事件。此方法仅负责向用户显示其属性。除非您有仅属于此组件的视觉信息(例如弹出窗口的可见性),否则不要使用状态。显示或更新的任何内容都来自上面:更高级别的组件或容器。它不决定更新自己的价值观。最好的情况是,它处理子组件上的用户事件,然后在上面冒泡另一个事件,并且......也许在某个时候,它的容器将返回一些新属性!
  • 容器:非常愚蠢的逻辑,包括将顶级组件包装到 redux 中,以便将事件插入到操作中,并将存储的某些部分插入到属性中
  • Redux thunk(或 redux observable):它是处理整个用户应用程序逻辑的。这个人是唯一知道触发什么以及何时触发的人。如果您的前端的一部分必须包含复杂性,那就是这个!
  • 减速器:定义如何组织存储中的数据,使其尽可能易于使用。
  • 存储:理想情况下每个顶级容器都有一个存储,这是唯一包含必须向用户显示的数据的存储。其他人不应该。

如果您遵循这些原则,您就永远不会遇到任何问题,例如“为什么这会被调用两次?以及......是谁制作的?为什么此时此刻?”

还有一点:如果你使用 redux,请使用不变性框架。否则,您可能会遇到问题,因为减速器必须是纯函数。为此,您可以使用一种流行的 immutable.js,但一点也不方便。已故的 ousider 实际上是一个杀手:immer(由作者或 mobx 制作)。