состояние не отображается на реквизит в Redux Saga - PullRequest
1 голос
/ 08 июля 2019

Я практикую саксофон.Я видел все подобные вопросы, но они мне не помогли.

На самом деле мои действия - это дипатч, выборка данных из URL и состояние меняется, но нет сопоставления с реквизитами.

Мой код

Home.js

class Home extends Component {

  render() {
    console.log(this.props);
    return (
      <View style={{ justifyContent: "center", alignItems: "center", flex: 1 }}>
        <Text>Welcome to Dog Saga</Text>
        <Button title={"Show Dog"} onPress={this.props.onRequestDog} />
        {this.props.loading ? (
          <ActivityIndicator size="large" color={"red"} />
        ) : this.props.error ? (
          <Text>Error Occured</Text>
        ) : (
          <Image
            source={{ uri: this.props.url }}
            style={{ width: 100, height: 100 }}
          />
        )}
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    url: state.url,
    loading: state.loading,
    error: state.error
  };
};

const mapDispatchToProps = dispatch => ({
  onRequestDog: () => dispatch(requestDog())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Home);

apiReducer.js

import {
  API_CALL_REQUEST,
  API_CALL_SUCCESS,
  API_CALL_FAILURE
} from "../actions/actionTypes";

const initialState = {
  url: "",
  loading: false,
  error: false
};

const apiReducer = (state = initialState, action) => {
  switch (action.type) {
    case API_CALL_REQUEST:
      return {
        ...state,
        url: "",
        loading: true,
        error: false
      };
    case API_CALL_SUCCESS:
      return {
        ...state,
        url: action.url,
        loading: false,
        error: false
      };
    case API_CALL_FAILURE:
      return {
        ...state,
        url: "",
        loading: false,
        error: true
      };
    default:
      return state;
  }
};

export default apiReducer;

apiSaga.js

import { takeEvery, call, put, all } from "redux-saga/effects";
import axios from "axios";
import * as types from "../actions/actionTypes";
import {
  requestDog,
  requestDogSuccess,
  requestDogError
} from "../actions/actions";

//watcher saga, watches for actions dispatached to the store , starts worker saga
export default function* watcherSaga() {
  yield takeEvery(types.API_CALL_REQUEST, workerSaga);
  //yield takeLatest(API_CALL_REQUEST, workerSaga);
}

// function that makes the api request and returns a Promise for response
function fetchDog() {
  return axios({
    method: "get",
    url: "https://dog.ceo/api/breeds/image/random"
  });
}

// worker saga: makes the api call when watcher saga sees the action
export  function* workerSaga() {

  try {

    //yield put(requestDog());
    const response = yield call(fetchDog);

    // dispatch a success action to the store with the new dog
    yield put(requestDogSuccess(response.data));
  } catch (error) {
    // dispatch a failure action to the store with the error
    yield put(requestDogError());
  }
}

Probem

RequestDog ​​хорошо обрабатывает данные, а URL-адрес изображения также восстанавливается, но в измененном состоянии в хранилище не отображается какой-либо компонент эффекта.означает, что изображение не загружается.

Изображение расскажет вам историю происходящего.

redux logger

1 Ответ

1 голос
/ 08 июля 2019

Возможно, вы пропустили apiReducer ключ состояния в вашем отображении:

const mapStateToProps = state => {
  return {
    url: state.apiReducer.url,
    loading: state.apiReducer.loading,
    error: state.apiReducer.error
  };
};

или просто:

const mapStateToProps = state => state.apiReducer;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...