Iam当前正在使用react native和mobx构建应用程序。我的问题是,更改了商店中的可观察值后,该组件未重新呈现。我的代码如下:
components / phoneNumberChange.js:
@inject('store')
@observer export class PhoneNumberChange extends React.Component{
renderPhoneInput = () => (
<React.Fragment>
<Button onPress={() => this.props.store.showCountryPicker()}>
<Text>Show picker</Text>
</Button>
</React.Fragment>
);
render = () => (
<React.Fragment>
<CountryCodePicker visible= {this.props.store.pickerVisible}/>
</React.Fragment>
);
}
screens / loginScreen.js:
import { Provider } from "mobx-react";
import { store } from "stores/phoneNumberChangeStore.js";
import { PhoneNumberChange } from "components/phoneNumberChange.js";
export class LoginScreen extends React.Component{
render = () => (
<Provider store={store}>
<PhoneNumberChange/>
</Provider
);
}
stores / phoneNumberChangeStore.js:
import { observable, action } from "mobx";
class PhoneNumberChangeStore {
@observable pickerVisible;
constructor(){
this.hideCountryPicker();
}
@action hideCountryPicker = () => {
this.pickerVisible = false;
}
@action showCountryPicker = () => {
this.pickerVisible = true;
}
}
export const store = new PhoneNumberChangeStore();
babel.config.js:
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
};
};
package.json:
{
"name": "myapp",
"main": "app/app.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"eject": "expo eject"
},
"dependencies": {
"@babel/plugin-proposal-decorators": "^7.3.0",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-preset-react-native": "^4.0.1",
"expo": "^32.0.0",
"mobx": "^5.9.0",
"mobx-react": "^5.4.3",
"prop-types": "^15.7.2",
"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"react-native-animatable": "^1.3.1",
"react-native-ui-kitten": "^3.1.2",
"react-navigation": "^3.3.2"
},
"devDependencies": {
"babel-preset-expo": "^5.0.0"
},
"private": true
}
当可见道具更改时,是否显示countryCodePicker。可以了但是,当我从商店更改值时,它不会更新并显示。我将不胜感激!
欢呼
答案 0 :(得分:1)
您要在default
中将商店单例导出为phoneNumberChangeStore.js
,但是要在PhoneNumberChangeStore
中导入命名的导出loginScreen.js
。
使用default
中的loginScreen.js
导出。 store属性也称为pickerVisible
,而不是countryCodePickerVisible
。
答案 1 :(得分:0)
找到了解决方案!我在实例上重新定义了渲染。
我将render = () => {..}
更改为render(){ return (...); }
欢呼!