I am tring to use the Mobx to manage my react-project's state,but I cannot get the props from the Provider by mobx-react.
This is my root element(I delete the router to simplify the question):
import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory} from "react-router";
import {Provider} from "mobx-react";
import store from "../store";
import App from "./app";
ReactDOM.render((
<Provider store={store}>
<App/>
</Provider>),
document.getElementById("content"));
and this is my childNode:
import React, {Component} from "react";
import {observer, inject, PropTypes} from "mobx-react";
#inject("store") #observer
export default class App extends Component {
constructor(props) {
super(props);
console.log(this.props.store);
}
render() {
return (
<div>
ab
</div>
)
}
}
App.propTypes = {
store: PropTypes.observableObject
};
But when I log the store,the result is undefined, and I don't know why I cannot get the store.
From the chrome devtools, I find the Provider has the store but App cannot get store,I am very confused.
My store is bellow:
import {observable} from "mobx";
class Store {
#observable count;
constructor() {
this.count = 1;
}
addCount() {
this.count += 1;
}
decreaseCount() {
this.count -= 1;
}
}
let store = new Store();
export default store;
Related
I'm trying to use the context router in a component and I can't understand why it is undefined.
After searching for similar questions I've tried different solutions, such as:
wrapped the withRouter hoc into my component
added the contextTypes with router
made sure that the App component is wrapped with BrowserRouter
tried to access the router with both this.props.router and this.context.router
This is my code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import { AppRedux } from 'components';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<Router>
<AppRedux />
</Router>
</Provider>,
document.getElementById('app')
);
AppRedux.js
import { connect } from 'react-redux';
import AppContainer from './AppContainer';
const mapDispatchToProps = (dispatch) => ({
// ...
})
const mapStateToProps = (state) => ({
// ...
})
export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
AppContainer.js - here is where I'm trying to access the context router
import React from 'react';
import { withRouter } from 'react-router'
class AppContainer extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
console.log(this.context) // { router: undefined }
console.log(this.props.router) // { router: undefined }
return (
// ...
);
}
}
AppContainer.contextTypes = {
router: PropTypes.object.isRequired
}
export default withRouter(AppContainer);
I am very new to React Native and in the process of creating some sample apps. So following a tutorial app, i was trying to create a Taxi Booking App that has redux store involved in it.
So my App.js file looks as below:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Root from "./src/main";
export default class TaxiApp extends Component {
render() {
return (
<View style={styles.container}>
<Root {...this.props}/>
</View>
);
}
}
The main.js file is as follows:
import React from "react";
import createStore from "./store/createStore";
import AppContainer from "./AppContainer";
export default class Root extends React.Component{
renderApp(){
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState);
return(
<AppContainer store={store}/>
);
}
render(){
return this.renderApp();
}
}
The AppContainer component is as follows:
import React, {Component, PropTypes} from "react";
import {Router} from "react-native-router-flux";
import {Provider} from "react-redux";
import scenes from "../routes/scenes";
export default class AppContainer extends Component{
static propTypes = {
store : PropTypes.object.isRequired
}
render(){
return(
<Provider store={this.props.store}>
<Router scenes={scenes}/>
</Provider>
)
}
}
The createStore() function for the Root component is as follows:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import makeRootReducer from "./reducers";
import { createLogger } from "redux-logger";
import createSocketIoMiddleware from "redux-socket.io";
import io from "socket.io-client/dist/socket.io";
let socket = io("http://localhost:3000", {jsonp:false});
let socketIoMiddleware = createSocketIoMiddleware(socket, "server/");
const log = createLogger({ diff: true, collapsed: true });
// a function which can create our store and auto-persist the data
export default (initialState = {}) => {
// ======================================================
// Middleware Configuration
// ======================================================
const middleware = [thunk, log, socketIoMiddleware];
// ======================================================
// Store Enhancers
// ======================================================
const enhancers = [];
// ======================================================
// Store Instantiation
// ======================================================
const store = createStore(
makeRootReducer(),
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
);
return store;
};
On trying to run this in the android emulator I am getting the following error:
undefined is not an object(evaluating '_react.PropTypes.object')
It would be great if someone could help. Thanks in advance!!!
You need to do the following
import PropTypes from 'prop-types';
remove import proptypes from the react package
I am trying to create a searchbox here, using redux but everytime I run the code, which appears to be flawless, some error creeps in. It shows that the state is undefined, followed by an error in webpack_require file from the node modules. Another time, it showed that the searchField is not defined. Any assistance would be highly appreciated.
Actions:
import { CHANGE_SEARCH_FIELD } from './constants.js';
export const setSearchField=(text)=>({
type: CHANGE_SEARCH_FIELD,
payload: text
})
Reducers:
import { CHANGE_SEARCH_FIELD} from './constants.js';
const initialState={
searchField: ''
}
export const searchRobots=(state=initialState, action={})=>{
switch(action.type){
case CHANGE_SEARCH_FIELD:
return Object.assign({},state,{searchField: action.payload});
default: return state;
}
}
index.js:
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import './index.css';
import 'tachyons';
import App from './App.js'
import * as serviceWorker from './serviceWorker';
import {searchRobots} from './reducers.js';
const store= createStore(searchRobots);
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
serviceWorker.register();
Container:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import CardList from './CardList';
import SearchBox from './SearchBox';
import Scroll from './Scroll';
import {setSearchField} from './actions.js'
import './App.css';
const mapStateToProps=(state)=>{
return {
searchField: state.searchRobots.searchField
}
}
const mapDispatchToProps=(dispatch)=>{
return {
onSearchChange: (event)=>{
dispatch(setSearchField(event.target.value))
}
}
}
class App extends Component{
constructor(){
super()
this.state={
robots: [],
}
}
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(
response=>{return response.json();}
)
.then(
users=>{this.setState({robots: users});}
);
}
render(){
const {searchField,onSearchChange}=this.props;
const filteredRobots= this.state.robots.filter(robot=>{return robot.name.toLowerCase().includes(searchField.toLowerCase())});
return(
<div className='tc'>
<h1 id="robo">ROBOFRIENDS</h1>
<SearchBox searchChange={onSearchChange}/>
<Scroll>
<CardList robots={filteredRobots} />
</Scroll>
</div>
);
};
}
export default connect(mapStateToProps,mapDispatchToProps)(App);
Any leads about the error would be highly appreciated
I'm getting below error even i had defined store for root component.
click to enlarge image
Not sure why im getting this error even after defining store.
index.js (rootpage)
import React, {Component} from 'react';
import {initStore} from './redux/store';
import {Provider} from 'react-redux';
import App from './App.container';
const store = initStore();
class BuddApp extends Component {
render () {
return (
<Provider store={store}>
<App />
</Provider>
);
}
}
export default BuddApp;
This is app.container.js which is inside app.
app/app.container.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Router from './routes';
import Proptypes from 'prop-types';
import {addNavigationHelpers} from 'react-navigation';
class App extends Component {
render () {
const {dispatch, nav, userPreferences} = this.props;
console.log(this.props)
return (
<Router screenProps={userPreferences} navigation={addNavigationHelpers({dispatch, state: nav})}/>
</Provider>
);
}
}
App.propTypes = {
dispatch: Proptypes.func,
nav: Proptypes.object,
userPreferences: Proptypes.object
};
const mapStateToProps = ({nav, userPreferences}) => ({
nav,
userPreferences
});
const mapDispatchToProps = (dispatch) => ({
dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
app/pages/login.page.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Login from '../components/Login/Login.component';
import {NavigationActions} from 'react-navigation';
class LoginPage extends Component {
onLoginPress(){
console.log("fsdfds")
this.props.navigation.navigate('setupProfile')
}
render () {
const {state} = this.props;
return (
<Login onLoginPress={this.onLoginPress.bind(this)} />
);
}
}
LoginPage.propTypes = {
onLoginPress: PropTypes.func
};
const mapStateToProps = (state) => ({
state:state
});
const mapDispatchToProps = (dispatch) => ({
saveLoginDetails: dispatch(addProfile(f))
});
export default connect(mapStateToProps,mapDispatchToProps)(LoginPage);
This results in getting the above mentioned error. as you can see I am passing the store in the same manner as shown in the redux example.
Am i defined store in wrong file?
Try this way:
import { createStore, applyMiddleware } from "redux"
const store = createStore(
<<Your combined reducers comes here>>,
applyMiddleware(<<All your middleware comes here>>))
I have parent grandchild dependency in my code.The main element is App.js
import React from 'react'
import ReactDOM from 'react-dom'
import {ExpenseApp} from './expense-app.js'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
import {FullBlog} from './FullBlog.js'
class App extends React.Component{
render(){
return(
<BrowserRouter>
<Route path='/' component={ExpenseApp}/>
<Route path='/fullblog' component={FullBlog}/>
</BrowserRouter>
)
}
}
ReactDOM.render(<ExpenseApp data={data}/>, document.getElementById('container'))
The expenseapp.js has a button through which I want another page to get loaded
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js';
import {Author} from './Author.js'
class ExpenseApp extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
list:[]
}
}
render(){
var data=this.state.data;
var list=this.state.list;
var len= Object.keys(data).length;
for(var i=0;i<len;i++){
//console.log(data[i]);
list.push(<Author key={i} i={i} data={data[i]}/>);
}
return(
<div>
{list}
</div>
)
}
}
module.exports={
ExpenseApp:ExpenseApp
}
the Author.js is like this
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js'
class Author extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
load:false,
content:'',
Author:'',
Book:''
}
this.loadBlog=this.loadBlog.bind(this);
}
loadBlog(i){
var that=this;
var data=this.state.data[i];
that.setState({
// load:true,
Content:this.props.data.Content,
})
that.context.Router.transitionTo(null,'/fullblog');
}
render(){
if(this.state.load===false){
return(
<div onClick={this.loadBlog} >
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
)
}//else{
// return(<Link to="/fullblog"><FullBlog data={this.state.data}/></Link>)
// }
}
}
Author.contextTypes = {
Router: function contextType() {
return React.PropTypes.func.isRequired;
}
};
module.exports={
Author:Author
}
And then there is FullBlog.js
class FullBlog extends React.Component{
render(){
return(<div>Hello world</div>)
}
}
module.exports={
FullBlog:FullBlog
}
And the error that I am getting is
But through this, I am not able to navigate to anything.I am using React-router for the first time and I dont know what the issue is. Thanks
You should use react routers withRouter() higher order function. You pass in your component and withRouter adds a router object to your component props.
import { withRouter } from 'react-router-dom';
// ...
export default withRouter(Author)
Then instead of calling Router.transitionTo (I'm not sure thats a thing) you would call this.props.router.history.push('/somepath')