Home > Mobile >  error message "undefined" when using Redux?
error message "undefined" when using Redux?

Time:12-24

It's my first time using redux and I'm trying to pass a state "apple" to a different component, but all I get is an error message saying "undefined is not an object(evaluating'_this.props.fruit') - does anyone understand what is going on here? (I've cleaned up the code for this example so it might be easier to see what the issue is so that why it looks kinda empty) Thank you!

App.js

    import { Provider } from 'react-redux'
    import {store} from './redux/app-redux'
const Stack = createStackNavigator()

export default function App() {
  return (
  
<Provider store={store}>
  <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen name="home" component={Home}/>
    </Stack.Navigator>
</NavigationContainer>
</Provider>
  );
}

app-redux.js

import {createStore, applyMiddleware} from 'redux'
import thunkMiddleware from 'redux-thunk'

const initialState = {
fruit: "apple"
}

const reducer= (state=initialState)=>{
return state
}

const store = createStore(reducer, applyMiddleware(thunkMiddleware))
export {store}

And Home.js

function mapStateToProps(state) {
    return{
        fruit: state.fruit
    }
}

const Home = () => {
    return(
    <View>
        <Text>{this.props.fruit}</Text>
    </View>
    )
}

export default connect(mapStateToProps)(Home)

CodePudding user response:

In functional component you don't need this keyword to read the props, actually props will pass as function argument. change your Home like this:

const Home = (props) => {
  return(
    <View>
      <Text>{props.fruit}</Text>
    </View>
   )
}

BTW react-redux has a useSelector method(hook). That's a much easier approach for functional components. See: https://react-redux.js.org/api/hooks#useselector

  • Related