Call state value of another script with redux

房东的猫 提交于 2020-01-22 02:31:11

问题


I want to call a speed value of Screen2.js to Screen1.js. I'm trying with redux, but I'm not very familiar with it.

I tried to create a store and return my speed value, and set my speed Screen1 for Screen2 speed.

Screen2.js

import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import Screen1 from './Screen1';
import { createStore } from 'redux';
import { Provider } from 'react-redux'
import { connect } from 'react-redux';

function mapStateToProps(state) {
    return {
        speed: state.speed  <<<<<< RETURN ERROR IN MY CONSOLE = UNDEFINED IS NOT AND OBJECT (STATE.SPEED)
    }
}

const mystore = createStore(mapStateToProps)

export default class Screen2 extends Component {

    constructor(props) {
        super(props)

        state = {
            speed: '2,4543',
        }
    }
    render() {
        return (

            <Provider store={mystore}>
            <Screen1 speed = {this.state.speed} />
            <View style={styles.MainContainer}>
                <Text style={{ fontSize: 23 }}> Screen 2 </Text>
                </View>
            </Provider>

        );
    }
}

Screen1.js

import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import Screen2 from './Screen2';
import { connect } from 'react-redux';
import { NavigationDrawerStructure } from '../App';

export default class Screen1 extends Component {

   constructor(props) {

        super(props)

        this.state = {

            speed:'' <<<<<< I WANNA UPDATE VALUE BY screen2.js

        }
    }

    render() {

        console.log(this.props.speed)

        return (

            <View style={styles.MainContainer}>
                <Text style={{ fontSize: 22 }}> Screen 1 </Text>


                <Text style={{ justifyContent: 'center', alignItems: 'center', marginTop: 17 }}>

                    myspeed: {this.props.speed} 
                </Text>
            </View>
        );
    }
}

MapStateToProps returns an error in my console:

Undefined is not an object (state.speed)

I saw many topics on this, but couldn't understand any of them.

来源:https://stackoverflow.com/questions/59557075/call-state-value-of-another-script-with-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!