我正在我的React Native应用程序中设置redux,并且努力让我的响应发送到reducer。我已经确认通过分派可以正确获得响应,因此后端可以正常工作。我在下面发布了很多代码,因为我有点迷路,但是我的前三个问题是:
这是我的代码:
1) 如果我没有正确连接,这就是我在使用该功能的组件底部将其连接的方式:
export default connect(null, { signup })(ApprovedScreen)
2)store.js
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const inititalState = {};
const store = createStore(
rootReducer,
inititalState,
applyMiddleware(thunk))
export default store;
3)authAction.js
import axios from 'axios'
import { LOG_IN } from './types'
export const signup = ({email, password}) => dispatch => {
axios.post('myapi.com/signup', {email, password})
.then(response =>dispatch({
type:LOG_IN,
payload: response.data.token
}))
.catch(error => {
console.log(error)
})
}
reducers / index.js(显然这在商店中自动称为rootReducer)
import { combineReducers } from 'redux'
import { authReducer } from './authReducer'
export default combineReducers({
auth: authReducer
})
authReducer.js
import { LOG_IN } from '../actions/types'
export const authReducer = (state = {loggedIn: null}, action) => {
switch (action.type) {
case LOG_IN:
console.log('the login reducer was activated!')
return {loggedIn: action.payload}
default:
return {...state}
}
}
来自我的App.js文件
const App = createAppContainer(switchNavigator);
export default () =>{
return (
<Provider store={store}>
<App />
</Provider>
)
}
我在其中调用signup()的文件(Screen.js)中的一些相关代码
import React, {useState} from 'react'
import { connect } from 'react-redux'
import { StyleSheet, View, Text, TextInput, Image, TouchableOpacity } from 'react-native';
import { signup } from '../../actions/authAction'
const Screen = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<View>
<TextInput
value={email}
onChangeText={text=>setEmail(text)}
placeholder='Email'
autoCapitalize='none'
autoCorrect={false}
textContentType='emailAddress'
keyboardType='email-address'
/>
<TextInput
value={password}
onChangeText={text=>setPassword(text)}
placeholder='Password'
autoCapitalize='none'
textContentType='newPassword'
secureTextEntry={true}
/>
<TouchableOpacity style={styles.submitButton} onPress={()=>signup({email, password})}>
<Text style={styles.submitButtonText}>Create An Account</Text>
</TouchableOpacity>
</View>
)
}
export default connect(null, { signup })(Screen)