问题
I'm trying to get data from api about currencies and I get error about NaN. I console.log(this.props)
There it is:
There is what I already did. In my actionTypes.js
export const FETCH_DATA_BEGIN = 'FETCH_DATA_BEGIN';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_FAIL = 'FETCH_DATA_FAIL';
and also there is my action.js
export const fetchData = () => {
return dispatch => {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.props.base}`)
.then(res => res.json())
.then(
data => dispatch(fetchDataSuccess(data)),
e => dispatch(fetchDataFail(e)),
);
};
};
next is my initialState
in my reducer and case actionTypes.FETCH_DATA_SUCCESS
const initialState = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR', 'PLN', 'GBP'],
base: 'EUR',
amount: '',
convertTo: 'PLN',
result: '',
date: '',
error: null,
loading: false,
rates: '',
};
case actionTypes.FETCH_DATA_SUCCESS:
const date = action.data.date;
const rates = action.data.rates;
return {
...state,
date,
rates,
loading: false,
};
next I'm using mapStateToProps and mapDispatchToProps in my component like this
const mapStateToProps = (state, ownProps) => {
return {
base: state.base,
amount: state.amount,
convertTo: state.convertTo,
result: (state.rates[ownProps.convertTo] * ownProps.amount).toFixed(4),
date: state.date,
};
};
const mapDispatchToProps = dispatch => {
return {
handleFirstSelect: itemValue =>
dispatch(exchangeCurriencesActions.handleFirstSelect(itemValue)),
handleSecondSelect: itemValue =>
dispatch(exchangeCurriencesActions.handleSecondSelect(itemValue)),
handleInput: text => dispatch(exchangeCurriencesActions.handleInput(text)),
fetchData: () => dispatch(exchangeCurriencesActions.fetchData()),
};
};
And my componendDidMount()
function is like that
componentDidMount() {
if (this.props.amount === isNaN) {
return;
} else {
try {
this.props.fetchData();
} catch (e) {
console.log('error', e);
}
}
}
And for example I'm using new props like this
<TextInputComponent
editable={false}
value={`${
this.props.amount === ''
? '0'
: this.props.result === null
? 'Calculating...'
: this.props.result
}`}
/>
and of course I added middleware
export default class App extends React.Component {
render() {
const store = createStore(exchangeCurrencies, applyMiddleware(thunk));
return (
<Provider store={store}>
<NavigationContainer>
<StatusBar hidden={true} />
<MainTabNavigator />
</NavigationContainer>
</Provider>
);
}
}
I'm adding a picture how does it look like in app
Where is the mistake? I can also add more code if its necessary. Please help someone !:D
来源:https://stackoverflow.com/questions/60565762/nan-problem-with-react-redux-and-react-thunk