Error modal sample with super outside constructor - react-native

Anyone can help me fix this error when using code modal sample in link https://facebook.github.io/react-native/docs/modal.html I can't understand why this error appear although i coded absolutely same code sample.

Use ES6 class. Constructor will work only on ES6 class.
class ModalExample extends React.Component {
constructor () {
super(props)
}
render () {
// code
}
}
If you don't want to use ES6 class, then use getInitialState to set the state.
var ModalExample = React.createClass ({
getInitialState: function() {
return {
modalVisible: false
}
}
})

Related

Having trouble with variables (this.x) in react native

I'm following this tutorial to try to get tensorflow js working in react native.
The tutorial's code is as follows (working, tested by cloning the repo):
class App extends React.Component {
state = {
isTfReady: false,
isModelReady: false,
predictions: null,
image: null
}
async componentDidMount() {
await tf.ready()
this.setState({
isTfReady: true
})
this.model = await mobilenet.load()
this.setState({ isModelReady: true })
this.getPermissionAsync()
}
While my code:
const modelJson = require('../assets/model/model.json');
const modelWeights = require('../assets/model/group1-shard1of1.bin');
class CameraCompo extends Component {
async componentDidMount(){
this.model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
}
Gives me the error: Property 'model' does not exist on type 'CameraCompo'
I've tried adding this.model into a constructor, as follows:
constructor(props){
super(props)
this.model = tf.GraphModel
}
But then, it simply gives me the same error.
Any help would be greatly appreciated.
Typescript is complaining that model is not a property of the component
An interface can be defined for the props and the state for typescript to infer them along the way. If not they can be simply set to any which defeats the purpose of using typescript
inferface Props {
// add what is necessary
}
interface State {
model: any
}
class CameraCompo extends Component<Props, State> {
async componentDidMount(){
const model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
this.setState(model)
// later model can be accessed with this.state.model.predict(input)
}
}
The above would be to define a model and set it in the state of the component. But the model hardly changes and there might probably not a need to keep it in the state of the component. In that case, model simply needs to be declared
class CameraCompo extends Component {
private model: any
async componentDidMount(){
this.model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
}
}

Destroyed component called 'updated' hook

Version
Vue#2.5.16
Vuex#3.0.1
VueRouter#3.0.1
Code
First my code looked like this
export default {
//...
updated () {
//TODO
}
destroyed () {
this.unregisterModule(module.name)
}
}
But when the app get other route, this component will call the updated once and cause some problems.
Now I use the _isDestroyed state property to resolve this:
updated () {
if (!this._isDestroyed) {
//TODO
}
}
Question
How to understand this logic of hooks?

Apollo resetStore doesn't work

please help;
I've got an error "undefined is not an object (evaluating 'this.props.client')
class FeedProfileBottom extends Component {
_onLogoutPress = function() {
this.props.client.resetStore();
return this.props.logout();
}
render() {
return (
<Root>
<LogOutButton onPress={this._onLogoutPress}>
<LogOutText>
Logout
</LogOutText>
</LogOutButton>
</Root>
);
}
}
export default withApollo(connect(undefined, { logout })(FeedProfileBottom));
You might need to explicitly bind the scope of your component to your function.
class FeedProfileBottom extends Component {
constructor (props) {
super(props);
this._onLogoutPress = this._onLogoutPress.bind(this);
}
// ...

Navigation - Pass variable to other files

I'm new on React-Native and it's my first React-Native app. However, I have already some problems.
I want to pass a variable from one class (Home.js) to an another. (Is it possible without using the composent in the render() fonction ?)
##### Home.js #####
class Home extends Component {
constructor(props) {
super(props);
this.state = {direction: "defaultvalue"};
}
getCurrentDirection() {
return this.state.direction;
}
render() {
/***..... some elements ..*/
}
}
export default Home
And
#### Two.js ####
import Home from './Home'
/** SOME CODE **/
const DrawerOptions = {
initialRouteName: Home.getCurrentDirection(),
contentComponent: CustomDrawerContentComponent,
drawerWidth: 300,
};
However it doesn't work... How to resolve it ? I have already try some solutions as declare the getCurrentDirection as static but nothing.
In addition, it seems to be a specific case because DrawerOptions is not a class. Could you please, add to your response also, how make it if I want to obtain the variable into the class Two.js ?
I meant if Two.js was for example :
##### Two.js #####
class Two extends Component {
var myvariable = Home.getCurrentDirection();
render() {
/***..... some elements ..*/
}
}
Thanks a lot in advance
A recommendable way of accessing the state from a component into another is to use (in this case) the Home component as a parent of Two component. This way you don't have to trigger a function to access the Home's state. On each time when the state of the parent (in this case) component will be updated, the Two component will receive the updated property (direction). If you want to call a function from Two component, you have to pass it a function as a property (changeCurrentDirection) that will call back the function you want to trigger from Home component.
So you would have something like this:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
direction: "defaultValue"
};
}
changeCurrentDirection() {
this.setState({
direction: "valueChanged"
})
}
render() {
let state = this.state;
return (
<Two
direction={state.direction}
changeCurrentDirection={() => this.changeCurrentDirection.bind(this)}/>
)
}
}
class Two extends React.Component {
render() {
let props = this.props;
return (
<div>
<h3>{props.direction}</h3>
<button onClick={props.changeCurrentDirection()}>Change value</button>
</div>
)
}
}
React.render(<Home/> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="app"></div>
Additional info you can find here.
Also, if you want to have a good management of the state of your components, my advice for you is to use redux. Using this library you can easily connect the component's actions and properties that can further be accessible from other files where you can manage them.

EventEmitter and Subscriber ES6 Syntax with React Native

I am trying to implement an EventEmitter/Subscriber relationship between two components in a react native class. I have seen referenced the following materials:
React Native - Event Emitters by Colin Ramsay
React Native - Call Function of child from NavigatorIOS
These solutions are adequate for what I am trying to accomplish, however, they bother require the use of mixins: [Subscribable.Mixin] on the receiving component to work properly with Subscriber. Unfortunately, I am using ES6 and extending my classes from Component so I can not use this mixin syntax.
My question is: How can I implement the above solutions in ES6 without the use of mixins?
You don't need mixins to use EventEmitters.
Simple demo:
import EventEmitter from 'EventEmitter';
let x = new EventEmitter();
function handler(arg) {
console.log(`event-name has occurred! here is the event data arg=${JSON.stringify(arg)}`);
}
x.addListener('event-name', handler);
x.emit('event-name', { es6rules: true, mixinsAreLame: true });
The full signature for addListener takes three args:
EventEmitter.addListener(eventName, handler, handlerContext)
In a react component, you likely want to use that context arg, so that the handler can be a class method instead of an inline function and still retain this == component instance. E.g.:
componentDidMount() {
someEmitter.addListener('awesome', this.handleAwesomeEvents, this);
// the generalist suggests the alternative:
someEmitter.addListener('awesome', this.handleAwesomeEvents.bind(this));
}
handleAwesomeEvents = (event) => {
let awesomeness = event.awesomeRating;
// if you don't provide context in didMount,
// "this" will not refer to the component,
// and this next line will throw
this.setState({ awesomeness });
};
FYI: I got this from looking at the decidedly unmagical implementation of the infamous Subscribable mixin. Google search results are basically an echo chamber of Ramsay's single mixin-based demo.
P.S. As far as exposing this emitter to another component, I'd probably have the owning component provide a function for receiving the emitter reference, and the component that creates the emitter would then conditionally execute that prop with the emitter.
// owner's render method:
<ThingThatEmits
onEmitterReady={(emitter) => this.thingEmitter = emitter}
/>
// inside ThingThatEmits:
componentDidMount() {
this.emitter = new EventEmitter();
if(typeof this.props.onEmitterReady === 'function') {
this.props.onEmitterReady(this.emitter);
}
}
This might be a very late answer, but I'm just going to put it out there for anyone who might find this useful.
As of the time of writing this answer (July, 2020), React Native has changed a lot since version 0.60.0+, you can either use an instance of EventEmitter, or statically call the DeviceEventEmitter methods.
Here is an example using EventEmitter:
import { EventEmitter } from 'events';
const newEvent = new EventEmitter();
// then you can use: "emit", "on", "once", and "off"
newEvent.on('example.event', () => {
// ...
});
Another example using the DeviceEventEmitter:
import { DeviceEventEmitter } from 'react-native';
// then you can directly use: "emit", "addListener", and "removeAllListeners"
DeviceEventEmitter.emit('example.event', ['foo', 'bar', 'baz']);
Hope that comes handy for anyone who still looking for a way to implement custom events in React Native.
I was able to get a workaround with react-mixin. Not sure how proper it is, but it works without any modification. The key is adding reactMixin(DetailView.prototype, Subscribable.Mixin); after the class definition.
Going off the example that is floating around for EventEmitter and Subscribable:
'use strict';
var reactMixin = require('react-mixin');
var React = require('react-native');
var EventEmitter = require('EventEmitter');
var Subscribable = require('Subscribable');
var {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS
} = React;
class MainView extends Component {
constructor(props){
super(props);
this.EventEmitter = new EventEmitter();
}
somethingHappenedFunction(){
this.EventEmitter.emit("update_event", { message: "hello from up here"});
}
//rest of the class
}
class DetailView extends Component {
componentDidMount(){
this.addListenerOn(this.props.events, 'update_event', this.miscFunction);
}
miscFunction(args) {
console.log("message: %s", args.message);
}
//rest of the class
}
reactMixin(DetailView.prototype, Subscribable.Mixin);
With react-native 0.69.0 I solved it like this:
import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';
const emitter = new EventEmitter();
emitter.addListener('event name', (...args) => console.log('emitted with', args));
emitter.emit('event name', { message: 'Foo' });