#react-native
Вопрос:
У меня есть собственное приложение react для управления задачами пользователей. Когда я открываю экран для обновления, он выдает предупреждение, которое я написал в заголовке. Когда я что-то меняю и нажимаю кнопку для сохранения, это выдает и ошибку. Ошибка внутри функции componentDidUpdate в if(this.props.error) возвращает значение true, не может обновить задачу.
import React from 'react'
import { ActivityIndicator, Alert, Text, TouchableHighlight, View } from 'react-native'
import { connect } from 'react-redux'
import TaskActions from './tasks.reducer'
import UserActions from '../../../shared/reducers/user.reducer'
import { Navigation } from 'react-native-navigation'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { taskEntityDetailScreen } from '../../../navigation/layouts'
import t from 'tcomb-form-native'
import styles from './tasks-entity-edit-screen-style'
let Form = t.form.Form
class TaskEntityEditScreen extends React.Component {
constructor(props) {
super(props)
Navigation.events().bindComponent(this)
this.state = {
formModel: t.struct({
id: t.maybe(t.Number),
task: t.String,
deadline: t.Date,
userId: this.getUsers(),
}),
formValue: { id: null },
formOptions: {
fields: {
id: {
hidden: true,
},
userId: {
testID: 'userIdInput',
label: 'User',
},
task: {
returnKeyType: 'next',
onSubmitEditing: () => this.form.getComponent('deadline').refs.input.focus(),
testID: 'taskInput',
},
deadline: {
mode: 'date',
testID: 'deadlineInput',
},
},
},
task: {},
isNewEntity: true,
}
if (props.data amp;amp; props.data.entityId) {
this.state.isNewEntity = false
this.props.getTask(props.data.entityId)
}
this.props.getAllUsers()
this.submitForm = this.submitForm.bind(this)
this.formChange = this.formChange.bind(this)
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.task !== prevState.task amp;amp; !prevState.isNewEntity) {
return { formValue: entityToFormValue(nextProps.task), task: nextProps.task }
}
return null
}
componentDidUpdate(prevProps) {
if (prevProps.updating amp;amp; !this.props.updating) {
if (this.props.error) {
Alert.alert('Error', 'Something went wrong updating the entity', [{ text: 'OK' }])
} else {
const entityId = this.props.task.id
this.props.reset()
this.props.getTask(entityId)
const alertOptions = [{ text: 'OK' }]
if (!this.state.formValue.id) {
alertOptions.push({
text: 'View',
onPress: taskEntityDetailScreen.bind(this, { entityId }),
})
}
Navigation.pop(this.props.componentId)
Alert.alert('Success', 'Entity saved successfully', alertOptions)
}
}
}
getUsers = () => {
const users = {}
this.props.users.forEach((user) => {
users[user.id] = user.login ? user.login.toString() : user.id.toString()
})
return t.maybe(t.enums(users))
}
submitForm() {
// call getValue() to get the values of the form
const task = this.form.getValue()
if (task) {
// if validation fails, value will be null
this.props.updateTask(formValueToEntity(task))
}
}
formChange(newValue) {
this.setState({
formValue: newValue,
})
}
render() {
if (this.props.fetching) {
return (
<View style={styles.loading}>
<ActivityIndicator size="large" />
</View>
)
}
return (
<View style={styles.container}>
<KeyboardAwareScrollView keyboardShouldPersistTaps={'handled'} testID="taskEditScrollView">
<Form
ref={(c) => {
this.form = c
}}
type={this.state.formModel}
options={this.state.formOptions}
value={this.state.formValue}
onChange={this.formChange}
/>
<TouchableHighlight style={styles.button} onPress={this.submitForm} underlayColor="#99d9f4" testID="submitButton">
<Text style={styles.buttonText}>Save</Text>
</TouchableHighlight>
</KeyboardAwareScrollView>
</View>
)
}
}
// convenience methods for customizing the mapping of the entity to/from the form value
const entityToFormValue = (value) => {
if (!value) {
return {}
}
return {
id: value.id || null,
task: value.task || null,
deadline: value.deadline || null,
userId: value.user amp;amp; value.user.id ? value.user.id : null,
}
}
const formValueToEntity = (value) => {
const entity = {
id: value.id || null,
task: value.task || null,
deadline: value.deadline || null,
}
if (value.userId) {
entity.user = { id: value.userId }
}
return entity
}
const mapStateToProps = (state) => {
return {
users: state.users.users || [],
task: state.tasks.task,
fetching: state.tasks.fetchingOne,
updating: state.tasks.updating,
error: state.tasks.errorUpdating,
}
}
const mapDispatchToProps = (dispatch) => {
return {
getAllUsers: (options) => dispatch(UserActions.userAllRequest(options)),
getTask: (id) => dispatch(TaskActions.taskRequest(id)),
getAllTasks: (options) => dispatch(TaskActions.taskAllRequest(options)),
updateTask: (task) => dispatch(TaskActions.taskUpdateRequest(task)),
reset: () => dispatch(TaskActions.taskReset()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TaskEntityEditScreen)