내 기존 앱 중 하나에 redux를 구현하려고합니다 (처음으로). 본질적으로 매우 간단한 작업을 수행하려면 텍스트 입력을 사용하여 문자열을 저장소에 저장하고 redux를 사용하여 다른 구성 요소에 다시 전달합니다. 그러나 액션이 전달되지만 콘솔에 기록 할 때 입력 한 문자열에 대해 '정의되지 않음'이 계속 표시됩니다. 내가 어디로 잘못 가고 있는지 확실하지 않고 다른 질문으로 초보자의 마음이 훨씬 명확하지 않습니다!
단일 감속기를 정의하고 색인에 결합하고 저장소를 생성하고 (결합 된 감속기를 전달), 내 저장소가있는 공급자에 래핑 된 탐색 (전체 앱)을 만들고, 디스패치를 활성화하기위한 디스패치 및 이벤트 / 액션을 생성했습니다 (기본적으로 사용자가 문자를 입력하고 계속 버튼을 누릅니다).
textInputPost.js : (감소 기)
const initialState = {
textInputValue: '',
};
const textInputReducer = (state = initialState, action) => {
console.log('textInputReducer', action);
switch(action.type){
case 'ADD_INPUT_TEXT':
return { textInputValue: action.text };
case 'RESET_INPUT_TEXT':
return { textInputValue: ''}
default:
return state;
}
}
export default textInputReducer;
index.js : (rootReducer-감속기 결합)
import { combineReducers } from 'redux';
import photoInputPost from './photoInputPost'
import cameraInputPost from './cameraInputPost'
import textInputPost from './textInputPost'
export default rootReducer = combineReducers({
text: textInputPost
})
Index.js : (스토어)
import { createStore } from 'redux'
import rootReducer from './../reducers/index'
export default Store = createStore(rootReducer)
App.js : (React Navigation을 감싸는 공급자)
return (
<Provider store={Store}>
<Navigation/>
</Provider>
);
AddTextModal.js : (textInput에서 스토어 상태를 업데이트하기위한 컴포넌트)
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, KeyboardAvoidingView, TextInput } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { FontAwesome5, Feather } from "@expo/vector-icons";
import { connect } from 'react-redux'
import ModalContainer from '../../App'
class AddTextModal extends React.Component {
continueUpload = (textInput) => {
this.props.addText(textInput)
console.log(this.props.textInputValue)
this.props.navigation.navigate('Upload')
}
render() {
return(
<View style={{backgroundColor:"#000000CC", flex:1}}>
<View style={{ backgroundColor:"#ffffff", marginLeft: 0, marginRight: 0, marginTop: 180, padding: 20, borderTopLeftRadius: 20, borderTopRightRadius: 20, flex: 1, }}>
<View style={styles.header}>
<TouchableOpacity style={{position: 'absolute'}} onPress={() => this.props.navigation.navigate('Home')}>
<Text style={styles.buttonFont}>Back</Text>
</TouchableOpacity>
<Text style={styles.headerText}>Write Something</Text>
<TouchableOpacity style={{position: 'absolute', right: 0}} onPress={(textInput) => this.continueUpload(textInput)}>
<Text style={styles.buttonFont}>Continue</Text>
</TouchableOpacity>
</View>
<View style={styles.uploadTextInput}>
<Feather name="message-square" size={14} color="grey" />
<TextInput style={{paddingLeft: 5, fontSize: 14}}
placeholder="What do you want to say?"
defaultValue={this.props.textInputValue}
onChangeText={textInput => this.props.addText(textInput)}
/>
</View>
</View>
</View>
);
}
}
//#6 mapStateToProps to access store from our component
function mapStateToProps(state){
return {
textInputValue: state.textInputValue
}
}
//#10. matchDispatchertoProps to establish dispatcher for actions. These actions will then go to functions in the reducer to change the app state
function mapDispatchToProps(dispatch) {
return {
addText: () => dispatch({type: 'ADD_INPUT_TEXT'}),
}
}
UploadScreen.js : (AddTextModal의 텍스트 입력 저장 상태 중계를위한 컴포넌트)
import React from 'react';
import { Text, Image, View, TextInput, TouchableHighlight, TouchableOpacity } from 'react-native';
import { FontAwesome5, Feather } from "@expo/vector-icons";
import { connect } from 'react-redux'
import ToolbarComponent from './ToolbarComponent'
import styles from './../Styles';
import textInput from './../../containers/textInput'
class UploadScreen extends React.Component {
uploadMedia = () => {
//upload to DB - add to vault, home screen
this.props.resetText()
this.props.navigation.navigate('Home')
}
//viewPhoto function for viewing photo on full screen
viewPhoto = () => {
return
}
render() {
return(
<View style={{backgroundColor:"#000000CC", flex:1}}>
<View style={{ backgroundColor:"#ffffff", marginLeft: 0, marginRight: 0, marginTop: 180, padding: 20, borderTopLeftRadius: 20, borderTopRightRadius: 20, flex: 1, }}>
<View style={styles.header}>
<TouchableOpacity style={{position: 'absolute'}} onPress={() => this.props.navigation.goBack()}>
<Text style={styles.buttonFont}>Back</Text>
</TouchableOpacity>
<TouchableOpacity style={{position: 'absolute', right: 10}} onPress={() => this.uploadMedia()}>
<Text style={styles.buttonFont}>Upload</Text>
</TouchableOpacity>
<View style={styles.uploadTextInput}>
<Text>{this.props.textInputValue}</Text>
</View>
</View>
</View>
</View>
);
}
}
function mapStateToProps(state){
return {
textInputValue: state.textInputValue
}
}
function mapDispatchToProps(dispatch) {
return {
resetText:() => dispatch({type: 'RESET_INPUT_TEXT'})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UploadScreen);
문제는 mapDispatchToProps 함수에 페이로드를 지정하지 않았다는 것입니다. mapDispatchToProps 함수를 다음과 같이 다시 작성해보십시오.
function mapDispatchToProps(dispatch) {
return {
addText: (payload) => dispatch({type: 'ADD_INPUT_TEXT', payload: payload}),
}
}
그리고 페이로드 이름을 'payload'로 변경 했으므로 감속기에서 'action.text'를 'action.payload'로 변경합니다.
const initialState = {
textInputValue: '',
};
const textInputReducer = (state = initialState, action) => {
console.log('textInputReducer', action);
switch(action.type){
case 'ADD_INPUT_TEXT':
return { textInputValue: action.payload };
case 'RESET_INPUT_TEXT':
return { textInputValue: ''}
default:
return state;
}
}
export default textInputReducer;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다