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)
,我可以看到相同的日志一遍又一遍地传递
就像 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,请使用不变性框架。否则,您可能会遇到问题,因为减速器必须是纯函数。为此,您可以使用一种流行的 immutable.js,但一点也不方便。已故的 ousider 实际上是一个杀手:immer(由作者或 mobx 制作)。
归档时间: |
|
查看次数: |
1352 次 |
最近记录: |