Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

reactjs - store.dispatch not updating props when called from outside of class

store.js

import AsyncStorage from "@react-native-community/async-storage";
import { createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import { createLogger } from "redux-logger";

import thunk from "redux-thunk";

import reducers from "../reducers";

const logger = createLogger({
  // ...options
});

const persistedReducer = persistReducer(persistConfig, reducers);

 export default () => {

  let store = createStore(persistedReducer, {}, applyMiddleware(thunk, logger));
  let persistor = persistStore(store);
  return { store, persistor };
};

PathexploredTab.js

import * as React from "react";
import {
  View,
  StyleSheet,
  Text,
  Dimensions,
  TouchableOpacity,
  Alert,
  Platform,
  Image
} from "react-native";
import { TabView, SceneMap, TabBar } from "react-native-tab-view";
import { Config } from "@common";
import { connect } from "react-redux";
import { compose } from "redux";
import { Dropdown } from "react-native-material-dropdown";
import { Field, reduxForm } from "redux-form";
import { ScrollView } from "react-native-gesture-handler";
import { Actions } from "react-native-router-flux";
import Icon from "react-native-vector-icons/Feather";
import {
  searchImmipaths,
  isKeepData,
  backToInitialState,
  continueFromPrevious,
  fetchDynamicFacts,
  pathExplorerTutorial
} from "../actions/path.actions";
import { checkConnection } from "../service/checkConnection";
import Loader from "./Loader";
import { colors, normalize, family, Images } from "@common";
import ResponsiveImage from 'react-native-responsive-image';
import { RFValue } from "react-native-responsive-fontsize";
import RNPicker from "rn-modal-picker";
import * as Animatable from 'react-native-animatable';
import UserinfoPopUp from "./../pages/UserinfoPopUp";
import { updateUserDetails, getUserDetails } from "../actions/auth.actions";
import AsyncStorage from "@react-native-community/async-storage";
import { copilot, walkthroughable, CopilotStep } from 'react-native-copilot';
import { StepNumberComponent } from "./../pages/newProfileScreen";
import persist from "./../config/store";
import Reactotron from 'reactotron-react-native'

const WalkthroughableImage = walkthroughable(Image);
const WalkthroughableText = walkthroughable(Text);
const WalkthroughableView = walkthroughable(View);
const WalkthroughableTouch = walkthroughable(TouchableOpacity);
const persistStore = persist();
const TooltipComponent = ({
  isFirstStep,
  isLastStep,
  handleNext,
  handlePrev,
  handleStop,
  labels,
  currentStep,
}) => {
  const handleDiscardTutorial = () => {
      Alert.alert(
          '',
          'are you sure you don’t want a tutorial on how to use the app?',
          [
            {
              text: 'yes',
              onPress: () => {AsyncStorage.setItem('DontShowTutorial', JSON.stringify(true)), handleStop()}
            },
            {
              text: 'Cancel',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel'
            },
          ],
          { cancelable: false }
        );
  }
  return (
      <View style={styles.tooltipContainer}>
          <Text testID="stepDescription" style={styles.tooltipText}>{currentStep.text}</Text>
          <View style={[styles.bottomBar]}>
              {
                  !isFirstStep ?
                      <TouchableOpacity style={styles.toolTipButton} onPress={handlePrev}>
                          <Text style={styles.toolTipButtonText}>{'Previous'}</Text>
                      </TouchableOpacity>
                      : null
              }
              {
                  !isLastStep ?
                      <TouchableOpacity style={styles.toolTipButton} onPress={handleNext}>
                          <Text style={styles.toolTipButtonText}>{'Next'}</Text>
                      </TouchableOpacity> :
                      <TouchableOpacity style={styles.toolTipButton} onPress={handleStop}>
                          <Text style={styles.toolTipButtonText}>{'Finish'}</Text>
                      </TouchableOpacity>
              }
               <TouchableOpacity onPress={() => persistStore.store.dispatch(pathExplorerTutorial('bbv'))}>
                  <Text style={styles.toolTipButtonText}>Go</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={handleDiscardTutorial}>
                  <Text style={styles.toolTipButtonText}>Do not show tutorial</Text>
              </TouchableOpacity>
          </View>
      </View>
  );
}
const window = Dimensions.get("window");
var width = window.width;
var height = window.height;
var immigrationInterst = [];
var countryIntrest = [];
let countryIntrestNow = [];
var FirstRoute = () => <View style={[{ height: height }]} />;

let disableButton = false;
var lastSearchedCountries = [];
var SecondRoute = () => <View style={[{ height: height }]} />;

class PathexploredTab extends React.Component {
  constructor(props) {
    super(props);
    this.imageMap = ['', Images.studyImage, Images.workImage, Images.residencyImage, Images.tourismImage];
    this.state = {
      isloading: false,
      buttonone: false,
      immibut1: false,
      immibut2: false,
      immibut3: false,
      immibut4: false,
      userInfoPopUpVisible: false, 
      countrybut1: false,
      countrybut2: false,
      countrybut3: false,
      countrybut4: false,
      filedsToShow: [],
      countrybut5: false,
      countrybut6: false,
      selectedval: "Select the Country",
      index: 0,
      routes: [
        { key: "first", title: "Select Goals" },
        { key: "second", title: "Select Countries" }
      ],
      checkconnection: false,
      errorMessage: "",
      isItemSelected: true,
      currentlySelectedItemIndex: -1,
      isItemChecked: true,
      checkboxData: ""
    };
  }
  componentDidUpdate = (nextProps) => {
    Reactotron.log('=====', nextProps.userPressedGo)
  }
  componentWillReceiveProps = (nextProps) => {
    

  }
  componentWillMount = async() => {
    const {
      getUser: { userDetails },
      authData: { token }
    } = this.props;
    this.props.dispatch(getUserDetails(userDetails.userid, token))
  }
  componentDidMount() {
    setTimeout(() => {
       this.props.start();
    }, 1000);
    immigrationInterst = [];
    countryIntrest = [];
    countryIntrestNow = [];
    const {
      getUser: { userDetails }
    } = this.props;
   
  
  }


  
  callProceed = () => {
     const {
      isItemSelected,
      currentlySelectedItemIndex,
      isItemChecked
    } = this.state;
    if (isItemSelected) {
      Alert.alert("Immigreat", "Please select any goal");
      return;
    }
    const lastGoal = this.props.immigationInterest[0]

    //This is a bit of a hacky fix but it works.
    let allPrevCountriesFound = lastSearchedCountries.every(ai => countryIntrestNow.includes(ai))
      && (lastSearchedCountries.length == countryIntrestNow.length);

    //We want to clear and search when:
    //a) There is no exploration id
    //b) Even if there is an exploration id but the lastGoal or last countries dont match
    //Note: We make one exception for if exploration id exists but the lastSearchedCountries is just an empty list

    let noExplorationId = (this.props.explorationId === "");
    let countryGoalDontMatch = (lastGoal != currentlySelectedItemIndex || !allPrevCountriesFound);
    let isProceedException = (lastSearchedCountries.length == 0 && !noExplorationId);

    noExplorationId || (!noExplorationId && countryGoalDontMatch && !isProceedException)
      ?
      this.clearAndSearch()
      : Alert.alert(
        "Immigreat",
        "Previous exploration found. Would you like to continue?",

        [
          {
            text: "START FROM BEGINNING",
            onPress: () => {
              this.props.dispatch(continueFromPrevious(0));
              this.props.dispatch(backToInitialState());
              this.props.dispatch(isKeepData(false));
              this._searchData();
            },
            style: "cancel"
          },
          {
            text: "CONTINUE",
            onPress: () => {
              lastSearchedCountries = [...countryIntrest];
              this.props.dispatch(isKeepData(true));
              this.props.didTapOnSearch();
            }
          },
          {
            text: "Cancel",
            onPress: () => console.log("Canceled"),
            style: "cancel"
          }
        ],
        { cancelable: false }
      );
  }
 
  
 
  _onPressBackButton = () => {
    this.setState(
      {
        isItemSelected: true,
        currentlySelectedItemIndex: -1,
        isItemChecked: false
      },
      () => {
        setTimeout(() => {
          this.intialLoadValues();
          //this.setState({ isItemSelected: true });
        }, 0);
      }
    );
  }

  extraOptionsRefresh() {
    const { currentlySelectedItemIndex, isItemChecked } = this.state;
    this.setState({ isItemChecked: !isItemChecked })
    switch (currentlySelectedItemIndex) {
      case 1:
        this.setState({checkBoxData:
          "Do you want to explore options you may have after your studies?"});
        break;
      case 2:
        this.setState({checkBoxData: 
          "Do you want to explore other goal options (such as studies) that can lead to work options?"});
        break;
      case 3:
        this.setState({checkBoxData:
          "Do you want to explore other goal options (such as studies or work) that could lead to permanent residency in the future?"});
        break;
      case -1:
        this.setState({checkBoxData: ""});
        break;
    }
  }

  intialLoadValues() {
    const { currentlySelectedItemIndex, isItemChecked } = this.state;
    /*var checkBoxData = "";
    switch (currentlySelectedItemIndex) {
      case 1:
        checkBoxData =
          "Do you want to explore options you may have after your studies?";
        break;
      case 2:
        checkBoxData = "Do you want to explore other goal options (such as studies) that can lead to work options?";
        break;
      case 3:
        checkBoxData =
          "Do you want to explore other goal options (such as studies or work) that could lead to permanent residency in the future?";
        break;
      case 4:
        checkBoxData = "";
        break;
    }*/

    FirstRoute = () => (
      <ScrollView style={{ flex: 1, backgroundColor: "white" }}>
        <Animatable.View animation="fadeIn" duration={1200} style={{ flex: 1 }}>
          <View
            style={{
              backgroundColor: "#DBDDDF",
              alignItems: "center",
              justifyContent: "center",
              flex: 1
            }}
  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem in this event:

onPress={store.dispatch(action)}

should be:

onPress={()=>store.dispatch(action)}

By the way you can connect your functional component like class component:

export default connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(TooltipComponent)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...