【发布时间】:2018-05-01 04:14:26
【问题描述】:
我正在尝试在我的 React Native 组件中使用新的 getDerivedStateFromProps 生命周期方法,但该方法从未被调用。我试过查找它,但在 react-native repo 中找到了no issues。在 StackOverflow 或 Google 上也没有结果。
我确实找到了 reddit thread 和 StackOverflow issue,它们都引用了更新 react-dom 作为解决方案,在这种情况下这不起作用,因为 React Native 中没有 dom。
谁能确认这个方法是否应该在 React Native 中工作?如果可以使用,任何解决这个问题的帮助将不胜感激。
以下是我的组件的简化版本:
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Auth } from '../redux';
import ChillaAPI from '../api';
const withUserData = WrappedComponent => {
class UserDataLoader extends React.Component {
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps');
if (props.uid !== state.uid) {
return {
uid: props.uid,
};
}
return state;
}
state = { uid: null };
render() {
console.log({ propsUid: this.props.uid });
console.log({ stateUid: this.state.uid });
return <WrappedComponent />;
}
}
UserDataLoader.propTypes = {
uid: PropTypes.bool.isRequired,
};
return connect(mapStateToProps)(UserDataLoader);
};
function mapStateToProps(state) {
return {
uid: Auth.selectors.getUid(state),
};
}
export default withUserData;
组件的日志输出如下:
{ propsUid: null }
{ stateUid: null }
{ propsUid: 'jW78ej3JDgPpheadAlcrkG8UIZB2' }
{ stateUid: null }
这是我的 package.json 的好方法:
{
"name": "Chilla",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"start:reset": "node node_modules/react-native/local-cli/cli.js start --reset-cache",
"watch:lint": "node node_modules/eslint-watch/bin/esw -w",
"test": "jest",
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": [
"node_modules/.bin/prettier --single-quote --trailing-comma es5 --write",
"eslint",
"git add"
]
},
"dependencies": {
"axios": "^0.18.0",
"firebase": "^4.13.1",
"husky": "^0.14.3",
"lint-staged": "^7.0.4",
"prop-types": "^15.6.1",
"react": "16.3.1",
"react-native": "^0.52.2",
"react-native-fetch-blob": "^0.10.8",
"react-native-image-picker": "^0.26.7",
"react-navigation": "^1.5.11",
"react-redux": "^5.0.7",
"recompose": "^0.27.0",
"redux": "^4.0.0",
"redux-logger": "^3.0.6"
},
"devDependencies": {
"babel-eslint": "^8.2.3",
"babel-jest": "22.4.3",
"babel-preset-react-native": "4.0.0",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.7.0",
"eslint-plugin-react-native": "^3.2.1",
"eslint-watch": "^3.1.4",
"jest": "22.4.3",
"prettier": "^1.12.1",
"react-test-renderer": "16.3.1"
},
"jest": {
"preset": "react-native"
}
}
【问题讨论】:
-
我可以确认静态函数 getDerivedStateFromProps() 按预期在 react-native 中工作,我正在使用它,因为我在 react v16.3 更新后重构了我的代码。我真的不明白为什么它不适合你。我假设您在编辑器中仔细检查了拼写并确认 react v16.3.1 确实已安装和编译?如果您使用的是模拟器,您也可以尝试删除该应用程序并重新安装。至少帮助了我好几次......
-
@dentemm 我做到了。现在想起来,大概是我的
react-native版本,我在v0.52.2上。您能否确认您至少使用的是 v0.55.0?
标签: javascript reactjs react-native