Андрей
все работает, но в базу не заносится
Archer
вы все что ли начали на ноде писать))
Archer
реакт нода
Archer
вот вы смешные)
Archer
не верно запрос пишешь полагаю
Андрей
я думал завернуть axios в функцию и вызывать ее при нажатии на кнопку, но не выходит
Archer
fetch('http://localhost:4000/business/add',{ method: 'post', body: { name:this.props.name, message:this.props.message } }).then(response =>this.props.addMessage(response.data) попробуй
Archer
а в ноде принемай данные с res.body
Archer
app.post('/business/add', (res, req) => { ..... })
Archer
как то так наверно у тебя
Андрей
дело в том, что когда у меня axios был в функциональной компоненте все работало
Андрей
да
Archer
onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:this.props.name, message:this.props.message }).then(response =>this.props.addMessage(response.data)) } componentDidMount() { this.onAddMessage() } <button onClick={()=>{this.componentDidMount()}}>Send</button>
Андрей
let onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:props.name, message:props.message }).then(response =>props.addMessage(response.data) ) }
Archer
подобная конструкция должна быть
Archer
то есть отдельный метод который делает запросы
Archer
и при клике его вызываешь
Андрей
попробую
Archer
ой стой
Archer
<button onClick={()=>{this.onAddMessage()}}>Send</button>
Archer
ошибка нельзя вызывать componentDidMount
Андрей
выдает ошибку props.onAddMessage is not a function
Ilya Parakhin
почему пропс?
Ilya Parakhin
this.onaddmessage или props.addmessage
Андрей
у меня там функциональная компонента
Андрей
я выношу axios
Андрей
в контейнер
Ilya Parakhin
Пробуй называть функции разнообразней, у тебя возможно путанница в названиях где что вызываешь.
Archer
если у тебя класс то у тебя нет такого ка кпрост
Archer
надо зис пропс
Андрей
я же перекинул его
Андрей
<Input updateNewPostText={this.props.updateNewPostText} updateNewNameText={this.props.updateNewNameText} addMessage={this.props.addMessage} name={this.props.name} message={this.props.message} onAddMessage={this.props.onAddMessage}/>
Archer
так ты лучше скрины скить эти файлов где у тебя работа налажена
Андрей
import React from 'react'; import {connect} from 'react-redux'; import {updateNewPostTextActionCreator,addMessageActionCreator, updateNewNameTextActionCreator} from '../../redux/messageReduser' import Input from './Input'; import {updadeDataActionCreator} from '../../redux/messageReduser' import * as axios from "axios"; class InputContainer extends React.Component{ constructor(props){ super(props) } componentDidMount() { this.onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:this.props.name, message:this.props.message }).then(response =>this.props.addMessage(response.data)) } } render() { return ( <Input updateNewPostText={this.props.updateNewPostText} updateNewNameText={this.props.updateNewNameText} addMessage={this.props.addMessage} name={this.props.name} message={this.props.message} onAddMessage={this.props.onAddMessage}/> ) } } const mapStateToProps = (state) => { return { name: state.messagesPage.name, message: state.messagesPage.message, } } const mapDispatchToProps = (dispatch) => { return { addMessage:(messages)=>{ dispatch(addMessageActionCreator(messages)); }, updateNewPostText:(post)=>{ let action=updateNewPostTextActionCreator(post); dispatch(action); }, updateNewNameText:(text)=>{ let action=updateNewNameTextActionCreator(text); dispatch(action); } } } export default connect(mapStateToProps, mapDispatchToProps)(InputContainer);
Андрей
вот контейнер
Archer
что это componentDidMount() { this.onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:this.props.name, message:this.props.message }).then(response =>this.props.addMessage(response.data)) } }
Андрей
import React from 'react'; import i from './Input.module.css'; import * as axios from "axios"; let Input =(props)=>{ let newNameElement=React.createRef(); let newMessageElement=React.createRef(); let onNameChange=()=> { let text = newNameElement.current.value; props.updateNewNameText(text); } let onMessageChange=()=> { let post = newMessageElement.current.value; props.updateNewPostText(post); } return( <div className={i.Input}> <input type={i.text} onChange={onNameChange} ref={newNameElement} placeholder={props.name} /> <input type={i.text} onChange={onMessageChange} ref={newMessageElement} placeholder={props.message} /> <button onClick={()=>{props.onAddMessage()}}>Send</button> </div> ) } export default Input
Archer
😕
Андрей
вот функциональная
Ilya Parakhin
Косяк
Ilya Parakhin
Обявляешь функцию в ComponentDidMount
Андрей
я сейчас только поправил
Ilya Parakhin
Вынеси обявление функции в тело класса, и вызывай её в компонентДидМоунт
Ilya Parakhin
Ут
Андрей
до этого не работало
Archer
addMessage={this.props.addMessage}
Archer
зачем ты её передаёшь? она делает у тебя запрос?
Ilya Parakhin
componentDidMount() { this.onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:this.props.name, message:this.props.message }).then(response =>this.props.addMessage(response.data)) }
Андрей
это диспатч
Ilya Parakhin
Ты Объявляешь её внутри а не вызываешь
Archer
ты мне скажи у тебя что сейчас выводит ?
Андрей
у меня просто заносит в локальный стейт
Archer
и мне интересно откуда у тебя метода в контейнере
Archer
const mapStateToProps = (state) => { return { name: state.messagesPage.name, message: state.messagesPage.message, } }
Андрей
тоесть axios не заносит данные
Archer
ты же только два поля взял с сторе
Archer
как ты остальное передаёшь?
Archer
а не стой
Андрей
ну я их и меняю
Archer
сам не заметил
Ilya Parakhin
class InputContainer extends React.Component{ constructor(props){ super(props) } componentDidMount() { this.onAddMessage=()=>{ axios.post('http://localhost:4000/business/add',{ name:this.props.name, message:this.props.message }).then(response =>this.props.addMessage(response.data)) } } render() { return ( <Input updateNewPostText={this.props.updateNewPostText} updateNewNameText={this.props.updateNewNameText} addMessage={this.props.addMessage} name={this.props.name} message={this.props.message} onAddMessage={this.props.onAddMessage}/> ) } }
Ilya Parakhin
Где ты объявляешь метод onAddMessage?
Ilya Parakhin
Объявление надо вынести в тело класса
Archer
смори
Андрей
я вынес
Ilya Parakhin
Что ты передаешь в Инпут?
Archer
в инпут ты передаёшь addMessage={this.props.addMessage}
Ilya Parakhin
this.PROPS.onAddMessage
Archer
а вызываешь {props.onAddMessage()}}
Ilya Parakhin
Где в пропсах класса onAddMessage - его там нет т.к. он метод класса а не пропса
Archer
onAddMessage у тебя делает запрос
Archer
addMessage как я понял сохраняет в стейт
Archer
попробуй вызывать addMessage
Archer
или так и задуманно при клике делать запрос?<button onClick={()=>{props.onAddMessage()}}>Send</button>
Андрей
c addMessage сообщения выводятся но не заносятся в базу
Андрей
сейчас по другому
Archer
ты же зачем то передал его в инпут addMessage
Ilya Parakhin
Да по клику он должен сделать запрос, потом сохранить. Он просто вместо this.onAddMessage написал this.props.onAddMessage
Ilya Parakhin
f tuj ytn d ghjgcf[